Loading

.Net Core Send Email

1、安装Nuget包MailKit,引用命名空间。

using MailKit.Net.Smtp;
using MimeKit;
注意:引用MailKit对应最新版本

2、定义收发地址和标题

MimeMessage message = new MimeMessage();
MailboxAddress from = new MailboxAddress("Admin","admin@example.com");
message.From.Add(from);
MailboxAddress to = new MailboxAddress("User", "user@example.com");
message.To.Add(to);
message.Subject = "This is email subject";
注意:Admin,User分别对应发送接收邮箱前缀

3、编写内容

BodyBuilder bodyBuilder = new BodyBuilder();
bodyBuilder.HtmlBody = "<h1>Hello World!</h1>";
bodyBuilder.TextBody = "Hello World!";
message.Body = bodyBuilder.ToMessageBody();
注意:也可以自定义模板,插入图片等等。

4、连接SMTP服务器发送邮件

SmtpClient client = new SmtpClient();
client.Connect("smtp_address_here", port_here, true);  //例如:smtp.exmail.qq.com,465
client.Authenticate("admin@example.com", "password"); //发送邮件的账户密码
client.Send(message);
client.Disconnect(true);
client.Dispose();

posted @ 2020-04-23 09:58  冬先生  阅读(494)  评论(0编辑  收藏  举报