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();