Send emails using MailKit

Page creation date :

environment

.NET
  • .NET 5.0
MailKit
  • 2.11.1

At first

Previously, smtpClient, a class for sending emails, was included as standard, but is now deprecated due to out-of-specifications.

This means that .NET does not have a standard mailing library, so you will use a third-party library.

Currently, there is "MailKit" as a mainstream library, so I would like to send an email using this time.

Introducing MailKit

Launch Visual Studio 2019 and create a new console app (.NET) project. If you're using .NET, you'll have some freedom in the project type, so I'll fore-know the details.

When you open the project, right-click Dependencies from Solution Explorer and select Manage NuGet Packages.

Click the Browse tab and type MailKit in the search field to display MailKit in the list below.

Select MailKit from the list, verify that the latest version is selected, and then click the Install button.

Click the OK button.

Verify that the package contains MailKit.

program

The following is the minimum code for sending emails.

You define the information you need for your emails at the first half of your code, and use those values to send mail in the second half. You should be able to use the second half of the code in a fixed way by simply changing the definition of the first half as needed.

using MailKit.Net.Smtp;
using MailKit.Security;
using MimeKit;
using MimeKit.Text;

namespace MailKitSend
{
  class Program
  {
    static void Main(string[] args)
    {
      // メールの送信に必要な情報
      var smtpHostName = "[SMTP サーバー名]";
      var smtpPort = 587;                         // or 25
      var smtpAuthUser = "[認証ユーザー名]";
      var smtpAuthPassword = "[認証パスワードまたはアプリパスワード]";

      // メールの内容
      var from = "[送信者メールアドレス]";
      var to = "[送り先メールアドレス]";

      var subject = "テストメールの件名です。";
      var body = "テストメールの本文です。\n改行です。";
      var textFormat = TextFormat.Text;

      // MailKit におけるメールの情報
      var message = new MimeMessage();

      // 送り元情報  
      message.From.Add(MailboxAddress.Parse(from));

      // 宛先情報  
      message.To.Add(MailboxAddress.Parse(to));

      // 表題  
      message.Subject = subject;

      // 内容  
      var textPart = new TextPart(textFormat)
      {
        Text = body,
      };
      message.Body = textPart;

      using var client = new SmtpClient();

      // SMTPサーバに接続  
      client.Connect(smtpHostName, smtpPort, SecureSocketOptions.Auto);

      if (string.IsNullOrEmpty(smtpAuthUser) == false)
      {
        // SMTPサーバ認証  
        client.Authenticate(smtpAuthUser, smtpAuthPassword);
      }

      // 送信  
      client.Send(message);

      // 切断  
      client.Disconnect(true);
    }
  }
}

Define the information needed to send an email

var smtpHostName = "[SMTP サーバー名]";
var smtpPort = 587;                         // or 25
var smtpAuthUser = "[認証ユーザー名]";
var smtpAuthPassword = "[認証パスワードまたはアプリパスワード]";

This is where you set different values depending on which mail server (SMTP server) you use. I'm'd like to explain a few of the values I'm setting at the end of this article, but basically see the site of my mail server.

Originally, it is written in appsettigs.json, etc., but it is forethough it becomes redundant as Tips.

Define the content of an email

var from = "[送信者メールアドレス]";
var to = "[送り先メールアドレス]";

var subject = "テストメールの件名です。";
var body = "テストメールの本文です。\n改行です。";
var textFormat = TextFormat.Text;

I think that this part is the corresponding part as it is if you normally use mailers etc.

Since it is not available to send from in disguise in recent mail systems, basically you will set the same email address as your email account.

TextFormat can be sent in text or HTML. If you send it in HTML, embed html tags in the body part.

Set up the information needed to process sending emails

// MailKit におけるメールの情報
var message = new MimeMessage();

// 送り元情報  
message.From.Add(MailboxAddress.Parse(from));

// 宛先情報  
message.To.Add(MailboxAddress.Parse(to));

// 表題  
message.Subject = subject;

// 内容  
var textPart = new TextPart(textFormat)
{
   Text = body,
};
message.Body = textPart;

Basically, it is a form of setting the value defined above.

You can also set multiple From and To.

It is not included in the sample, but it can also include CC and BCC. If you want to include it, add it in the same way as From or To as follows:

message.Cc.Add(MailboxAddress.Parse(cc));
message.Bcc.Add(MailboxAddress.Parse(bcc));

You can also change the display name of the sender or destination if the recipient of the email is supported. In that case, change the code as follows:

message.From.Add(new MailboxAddress("送信者の名前", from));
message.To.Add(new MailboxAddress("送り先の名前", to));

Send email

using var client = new SmtpClient();

// SMTPサーバに接続  
client.Connect(smtpHostName, smtpPort, SecureSocketOptions.Auto);

if (string.IsNullOrEmpty(smtpAuthUser) == false)
{
   // SMTPサーバ認証  
   client.Authenticate(smtpAuthUser, smtpAuthPassword);
}

// 送信  
client.Send(message);

// 切断  
client.Disconnect(true);

When you're done defining your email, you're done sending it.

Submission is SmtpClient done in an instance of the class. Dispose Because it using var is the target, it is declared in so that it can be released automatically. Since it is a way of writing C# 8.0, please change to the using normal description for earlier versions.

SmtpClient.Connect method to the SMTP server. Some STMP servers require SSL or TLS connections, but SecureSocketOptions.Auto specifying is usually fine.

If the SMTP server requires authentication, SmtpClient.Authenticate specify a user name and password in the method.

When the connection is SmtpClient.Send complete, send an email in the method.

When everything is done, SmtpClient.Disconnect disconnect it with the method.

Note that this tips all perform these operations as synchronous operations, but each method can also perform asynchronous processing under the name xxxxxAsync. Use as needed.

How to send attachments

To send an MimeMessage.Body attachment, change the value set to as follows:

// using System.IO; 必要

var filePath = @"[ローカルに保存されているファイルパス].jpg";   // 例として JPEG ファイル指定
var buffer = File.ReadAllBytes(filePath);

var builder = new BodyBuilder();

// テキストか HTML で設定するプロパティが異なる
if (textFormat == TextFormat.Plain)
{
   builder.TextBody = body;
}
else
{
   builder.HtmlBody = body;
}

// 添付ファイルを追加
builder.Attachments.Add(Path.GetFileName(filePath), buffer, new ContentType("image", "jpg"));

message.Body = builder.ToMessageBody();

In the above code, the file stored locally is an attachment, but the data can be anything because it only has to be a byte array or Stream. Sending a JPEG file as an example.

MimeMessage.Body The value you set to BodyBuilder build as .

Body text TextPart differs from , and the properties to which it is set are different, whether text or HTML. Please note that even if you set both, the first setting will be erased.

The attachment is BodyBuilder.Attachments added to the property. The arguments are "attachment name", "attachment data", and "content type (MIME)".

Note that the name of the attachment may not be identified by the receiving party unless you add an extension.

ContentType the value you set to will vary depending on the file format. If you search on the Internet around the "file format MIME", you will be can see the combination.

BodyBuilder.ToMessageBodyFinally, call the method and set it to MimeMessage.Body .

About specifying an SMTP server

The SMTP server for sending mail has different settings depending on the mail server you use. The following is an example, so if there is no such thing, please check the help of the server you are using.

In addition, since the information is as of April 2021, the information may have changed at present.

Mail service SMTP server port authentication If you are using two-step verification encryption
Outlook.com Part 1 smtp.office365.com 587 User name and password ?? STARTTLS
Outlook.com Part 2 smtp-mail.outlook.com 587 User name and password Get app password and set it to password STARTTLS
Gmail smtp.gmail.com 465(SSL) or 587(TLS) User name and password Get app password and set it to password SSL or TLS or STARTTLS
Yahoo! Mail smtp.mail.yahoo.co.jp 465 User name and password ?? Unknown type
OCN smtp.ocn.ne.jp 465 User name and password ?? SSL or TLS