LoginSignup
5
14

More than 3 years have passed since last update.

C#でメール送信する

Last updated at Posted at 2020-04-23

mailkitを使います。
Visual StudioのNuGetパッケージ管理画面で「MailKit」を検索してインストールする

mailtest.cs
var host = "smtp server name";
var port = 25 or 465 or 587;

using (var smtp = new MailKit.Net.Smtp.SmtpClient())
{
    try{
        //開発用のSMTPサーバが暗号化に対応していないときは、次の行をコメントアウト
        //smtp.ServerCertificateValidationCallback = (s, c, h, e) => true;
        smtp.Connect(host, port, MailKit.Security.SecureSocketOptions.Auto);
        //認証設定
        smtp.Authenticate("id", "password");

        //送信するメールを作成する
        var mail = new MimeKit.MimeMessage();
        var builder = new MimeKit.BodyBuilder();
        mail.From.Add(new MimeKit.MailboxAddress("", "送る人のメールアドレス"));
        mail.To.Add(new MimeKit.MailboxAddress("", "配信先のメールアドレス"));
        mail.Subject = "メールタイトル";
        MimeKit.TextPart textPart = new MimeKit.TextPart("Plain");
        textPart.Text = "メール本文";
        string filename = "添付ファイルの名前";
        //添付ファイルがあった時の処理
        if (!string.IsNullOrEmpty(filename))
        {
            var filePath = Server.MapPath("~/App_Data/doc/" + filename);
            var mimeType = MimeKit.MimeTypes.GetMimeType(filePath);
            var attachment = new MimeKit.MimePart(mimeType);
            using (var file = File.OpenRead(filePath))
            {
                attachment.Content = new MimeKit.MimeContent(file);
                attachment.ContentDisposition = new MimeKit.ContentDisposition();
                attachment.ContentTransferEncoding = MimeKit.ContentEncoding.Base64;
                attachment.FileName = Path.GetFileName(filePath);
                var multipart = new MimeKit.Multipart("mixed");
                multipart.Add(textPart);
                multipart.Add(attachment);
                mail.Body = multipart;
                //メールを送信する
                smtp.Send(mail);
            }
         }
         else
         {
            var multipart = new MimeKit.Multipart("mixed");
            multipart.Add(textPart);
            mail.Body = multipart;
            //メールを送信する
            smtp.Send(mail);
         }
    }
    catch(Exception exception)
    {
         Console.WriteLine(exception.Message);
    }
    finally
    {
    //SMTPサーバから切断する
    smtp.Disconnect(true);
    }
}


多分コピペで行けるはず

5
14
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
5
14