LoginSignup
7
2

More than 3 years have passed since last update.

asp.net core 3.0 でメールを送ってみる

Last updated at Posted at 2019-10-14

MailKit

SmtpClient Classは使えなくなっている

MailKit(https://github.com/jstedfast/MailKit)を使えばいいらしいんだが、検索してみると
ここがヒット
https://showylee.qrunch.io/entries/7fMcZM53WUZFTTvd
ここのサンプルコードでほぼほぼ動作する
あ、私がコピペした段階では多少問題ありでしたが
少し手を入れました

'''

public interface IMailSendLogic
{
    void SendMailAsync(string to, string from, string subject, string text);
}

public class MailSendLogic : IMailSendLogic
{
    private string SmtpHost = "";
    private int SmtpPort = 587;
    private string User = "";
    private string Pass = "";
    public async void SendMailAsync(string to, string from, string subject, string text)
    {
        var message = new MimeKit.MimeMessage();
        // 送り元情報  
        message.From.Add(new MimeKit.MailboxAddress("<送信者名>", from));
        // 宛先情報  
        message.To.Add(new MimeKit.MailboxAddress("<宛名>", to));
        // 表題  
        message.Subject = subject;
        // 内容  
        var textPart = new MimeKit.TextPart(MimeKit.Text.TextFormat.Plain);
        textPart.Text = text;
        message.Body = textPart;

        using (var client = new MailKit.Net.Smtp.SmtpClient())
        {
            try
            {
                // SMTPサーバに接続  
                await client.ConnectAsync(SmtpHost, SmtpPort);
                Debug.WriteLine("接続完了");

                // SMTPサーバ認証(あれば)  
                await client.AuthenticateAsync(User, Pass);

                // 送信  
                await client.SendAsync(message);

                // 切断  
                await client.DisconnectAsync(true);

            }
            catch (Exception e)
            {
                Debug.WriteLine("{0} Exception caught.", e);
            }
        }
    }
}

'''

nugetから取得します

image.png

core 3.0で確認しました。

Githubにも上げました

7
2
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
7
2