# 导包

  首先我们需要导入 mailkit nuget包,nuget安装包命令在下方拓展介绍中。

 

# 引用命名空间

using mailkit.net.smtp;
using mimekit;

 

# 邮件发送帮助类

        /// <summary>
        /// 发送邮件
        /// </summary>
        /// <param name="name">发件人名字</param>
        /// <param name="receive">接收邮箱</param>
        /// <param name="sender">发送邮箱</param>
        /// <param name="password">邮箱密码</param>
        /// <param name="host">邮箱主机</param>
        /// <param name="port">邮箱端口</param>
        /// <param name="subject">邮件主题</param>
        /// <param name="body">邮件内容</param>
        /// <returns></returns>
        public async task<bool> sendmailasync(string name, string receive, string sender, string password, string host, int port, string subject, string body)
        {
            try
            {
          # mimemessage代表一封电子邮件的对象
                var message = new mimemessage();
          # 添加发件人地址 name 发件人名字 sender 发件人邮箱
                message.from.add(new mailboxaddress(name, sender));
          # 添加收件人地址
                message.to.add(new mailboxaddress("", receive));
          # 设置邮件主题信息
                message.subject = subject;
          # 设置邮件内容
                var bodybuilder = new bodybuilder() { htmlbody = body };
                message.body = bodybuilder.tomessagebody();
                using (var client = new smtpclient())
                {
                    // for demo-purposes, accept all ssl certificates (in case the server supports starttls)
                    client.servercertificatevalidationcallback = (s, c, h, e) => true;
                    // note: since we don't have an oauth2 token, disable  
                    // the xoauth2 authentication mechanism.  
                    client.authenticationmechanisms.remove("xoauth2");
                    client.checkcertificaterevocation = false;
                    //client.sslprotocols = system.security.authentication.sslprotocols.tls12;
                    client.connect(host, port, mailkit.security.securesocketoptions.auto);
                    // note: only needed if the smtp server requires authentication
                    client.authenticate(sender, password);
                    await client.sendasync(message);
                    client.disconnect(true);
                    return true;
                }
            }
            catch (exception ex)
            {
            }
            return false;
        }

 借助这一个简单的邮件发送类我们就可以已经可以实现邮件发送功能了。

 

# 拓展(nuget常用命令) 

1、安装指定版本:install-package <程序包名> -version <版本号>

2、更新包:update-package <程序包名>

3、重新安装所有nuget包(整个解决方案都会重新安装)
  update-package -reinstall

4、重新安装指定项目所有nuget包
  update-package -project <项目名称> -reinstall

5、正常卸载:uninstall-package <程序包名>

6、强制卸载:uninstall-package <程序包名> -force

 

# 参考博文

https://blog.csdn.net/sd7o95o/article/details/89334103