備忘録

備忘録

C#でMailKitを利用してSMTPでメールを送信する方法

Ⅰ. はじめに

タイトルの通り「C#でMailKitを利用してSMTPでメールを送信する方法」です。

Ⅱ. 手順

1. 必要なパッケージをインストールする
Install-Package MailKit
2. サンプルプログラムを書く
using MailKit.Net.Proxy;
using MailKit.Net.Smtp;
using MailKit.Security;
using MimeKit;

using var client = new SmtpClient()
{
    // LocalDomain = "127.0.0.1",
    ServerCertificateValidationCallback = (s, c, h, e) => true,
    ClientCertificates = null,
    LocalEndPoint = null,
    Timeout = (int)TimeSpan.FromMinutes(1).TotalMilliseconds,
    // ProxyClient = new Socks5Client("127.0.0.1", 1080)
};

var smtpHost = "smtp.gmail.com";
var smtpPort = 465;
var emailAddress = "user001@gmail.com";
var password = "mypassword";
var toMailAddress = "user001@example.com";
var subject = "subject";
var body = "hello world";

client.Connect(smtpHost, smtpPort, SecureSocketOptions.Auto);
client.Authenticate(emailAddress, password);

var mail = new MimeMessage();
var builder = new BodyBuilder();

// mail.From.Add(new MailboxAddress("my name", emailAddress));
InternetAddress.TryParse(emailAddress, out var _emailAddress);
mail.From.Add(_emailAddress);
InternetAddress.TryParse(toMailAddress, out var _toMailAddress);
mail.To.Add(_toMailAddress);
mail.Subject = subject;
builder.TextBody = body;
mail.Body = builder.ToMessageBody();
client.Send(mail);

実行結果

省略

FAQ

Q. Linuxで以下メッセージが表示されてメールが送信できません
MailKit.Security.SslHandshakeException
An error occurred while attempting to establish an SSL or TLS connection.

This usually means that the SSL certificate presented by the server is not trusted by the system for one or more of
the following reasons:

1. The server is using a self-signed certificate which cannot be verified.
2. The local system is missing a Root or Intermediate certificate needed to verify the server's certificate.
3. A Certificate Authority CRL server for one or more of the certificates in the chain is temporarily unavailable.
4. The certificate presented by the server is expired or invalid.
5. The set of SSL/TLS protocols supported by the client and server do not match.
6. You are trying to connect to a port which does not support SSL/TLS.

See https://github.com/jstedfast/MailKit/blob/master/FAQ.md#SslHandshakeException for possible solutions.

A. 以下2つを試して下さい
1. MailKitのFAQ
https://github.com/jstedfast/MailKit/blob/master/FAQ.md#SslHandshakeException
2. OpenSSLのセキュリティレベルを変更する(下げる)
https://kagasu.hatenablog.com/entry/2021/12/17/194300