0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

MimeKitを利用したSmtp送信

Posted at

https://chawatoyo.blog.fc2.com/blog-entry-91.html
を参考にMimeKitを利用してSmtpでメールを送る処理
BodyBuilderクラスを使用
メール送信の処理は上記参考ブログになかったので記載

C#
using MimeKit;
using System.Security.Authentication;

///mailModelはメールの情報を詰め込んだモデルクラス
private void CreateMailContent(mailModel mailModel)
{
    var msg = new MimeKit.MimeMessage();
    msg.From.Add(new MailboxAddress(mailModel.from, mailModel.from));//表示名と実際のメールアドレス
    msg.To.Add(new MailboxAddress(mailModel.to, mailModel.to));
    msg.Subject = mailModel.title;

    //メール本文
    var builder = new BodyBuilder { TextBody = mailModel.content };

    //ファイル追加
    builder.Attachments.Add("ファイル1");
    builder.Attachments.Add("ファイル2");
    msg.Body = builder.ToMessageBody();
    //メール送信
    SendBySmtp(mailModel, msg);
}

private void SendBySmtp(MailModel mailModel, MimeMessage msg)
{
    using (var client = new MailKit.Net.Smtp.SmtpClient())
    {
        //次の2つはおまじない的なもの
        //Ssl3は旧形式ですの警告がでているものの、これを削るとエラーになる
        client.ServerCertificateValidationCallback = (s, c, h, e) => true;
        client.SslProtocols = SslProtocols.Ssl3 | SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12 | SslProtocols.Tls13;

        client.Connect(mailModel.host, mailModel.port, true);
        client.Authenticate(mailModel.user, mailModel.userPw);
        client.Send(msg);
        client.Disconnect(true);
    }
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?