Location>code7788 >text

Using MailKit to send and receive emails in C#

Popularity:55 ℃/2024-10-15 09:17:35

catalogs
  • Get QQ mailbox authorization code
  • Install MailKit
  • Configuring mail server information
  • Realize the method of sending and receiving mails
  • Test mail sending and receiving
  • reference article

Get QQ mailbox authorization code

Open QQ mailbox and enterSettings->Account Page:
image

existPOP3/IMAP/SMTP turn onSMTP serviceand then clickauthorization codeCopy the authorization code:
image

The parameters of QQ mailbox server are as follows, for details refer toSMTP/IMAP services

  • Receive mail server:If you are using SSL, port 993 is used.
  • Send mail server:If you are using SSL, use port 465 or 587.

The parameters of the NetEase mailbox server are as follows, for details refer toHow to set the parameters of Netease mailbox server?
image

Install MailKit

Install the MailKit library in your project, either by installing it via the NuGet package manager or by using the following command:

dotnet add package MailKit

MailKit Yes, it is.MimeKit A cross-platform email client library built on top of the NET, with the goal of becoming the best email framework for .

Configuring mail server information

Configure mail server information, including host, port, user name, password, etc., encapsulated into EmailData class:

/// <summary>
/// Mail Data
/// </summary>
class EmailData
{
    /// <summary>
    /// From: (email header)
    /// </summary>
    public string From { get; set; }
    /// <summary>
    /// authorization code
    /// </summary>
    public string Password { get; set; }
    /// <summary>
    /// To: (email header)
    /// </summary>
    public string To { get; set; }
    /// <summary>
    /// thematic
    /// </summary>
    public string Subject { get; set; }
    /// <summary>
    /// Plain text content
    /// </summary>
    public string TextBody { get; set; }
    /// <summary>
    /// HTMLelement
    /// </summary>
    public string HtmlBody { get; set; }

    /// <summary>
    /// Delivery Mail Server
    /// </summary>
    public HostInfo SMTP { get; set; }
    /// <summary>
    /// Accepting mail servers
    /// </summary>
    public HostInfo IMAP { get; set; }
}
/// <summary>
/// Server Information
/// </summary>
class HostInfo
{
    /// <summary>
    /// server address
    /// </summary>
    public string Host { get; set; }
    /// <summary>
    /// server port
    /// </summary>
    public int Port { get; set; }
}

Realize the method of sending and receiving mails

The method of sending and receiving emails is as follows, only the latest 10 emails are received here to facilitate the realization of interactive logic:

static async Task SendEmail(EmailData data)
data
    data
    {
        // Create a new MIME message object
        var message = new MimeMessage(); // Create a new MIME message object.

        // Set the sender
        (()).

        // Set the recipient
        (()).

        // Set the subject
         = ;

        // Set the body
         = new BodyBuilder
        {
            TextBody = ,
            HtmlBody =
        }.ToMessageBody(); }

        // Send an email using an SMTP client
        using (var client = new SmtpClient())
        {
            await (, , ); // send the message using the SMTP client

            // Note: Usernames and passwords should be kept safe and not hardcoded into the source code.
            await (, ); // Note: username and password should be kept safe and not hardcoded into the source code.

            // Send the email
            await (message);

            // Disconnect from the server
            await (true); // Disconnect from the server.
        }

        ("The email was successfully sent!") ;
    }
    catch (Exception ex)
    {
        ($"Mail delivery failed: {}"); }
    }
}

static async Task GetEmail(EmailData data)
{
    async Task GetEmail(EmailData) { data
    {
        // Connect to the IMAP server
        using (var client = new ImapClient())
        { await (, , true); // Usually TLS encryption is used.
            await (, , true); // Normally encrypted with TLS.

            // Authenticate the user
            await (, ); // Usually use TLS encryption // to authenticate the user.

            // Select the inbox
            var inbox = ;
            await (); // Select inbox.

            // Get the number of messages
            int totalMessages = ;
            // Make sure the start position is not less than 1
            int start = (totalMessages - 5, 1); int end = totalMessages; // Make sure the start position is not less than 1.
            int end = totalMessages; // Make sure the start position is not less than 1.


            // Get the latest 10 messages
            var messages = (start, end, | ); // Get the latest 10 messages.

            // Iterate through the messages and print them out
            foreach (var summary in messages)
            {
                var uid = ;
                var message = await (uid); ($"Subject: {}")
                ($"Subject: {}"); ($"From: {}"); var message = await (uid)
                
                
                
            }
            // Disconnect
            await (true); }
        }
    }
    catch (Exception ex)
    {
        ($"Failed to receive mail: {}"); }
    }
}

Note that the content of the Accepted E-mails section requires special parsing rules and cannot be printed directly from the ToString() method.

Test mail sending and receiving

Replace key information with your own when using:

static async Task Main(string[] args)
var data = new EmailData(string[] args)
    var data = new EmailData
    From = "qqqqqq@", var data = new EmailData {
        From = "qqqqqqq@",
        Password = "**********",
        To = "qqqqqqq@",
        Subject = "A test email from .NET Core",
        TextBody = "This is plain text message content." ,
        HtmlBody = "<h1>This is the HTML message </h1><p>This email was sent from .NET Core via MailKit. </p>",
        SMTP = new HostInfo()
        {
            Host = "",
            Port = 587
        },
        IMAP = new HostInfo()
        {
            Host = "",
            Port = 993
        }

    }.

    await SendEmail(data);
    await GetEmail(data); }
}

reference article

  • A complete example of using MailKit to send and receive emails in .NET Core
  • Get and use authorization code for QQ mailbox