NetCore 发送邮件

Net Core2.0出来后,已经自带了邮件服务。但是对于低版本来说,是无法使用自带的邮件服务的,只能通过第三方工具来实现。

这里我简单说一下使用MailKit这个包来发送邮件

1. 安装MailKit NuGet包。

2. 实现方法

using MimeKit;
using MailKit.Net.Smtp;


public void SendMail()
        {
            try
            {
                var message = new MimeMessage();
                message.From.Add(new MailboxAddress("xxx@163.com"));
                message.To.Add(new MailboxAddress("xxx@163.com"));

                message.Subject = "星期天去哪里玩?";

                message.Body = new TextPart("plain") { Text = "我想去故宫玩,如何" };

                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;

                    client.Connect("smtp.163.com", 587, true);

                    // Note: since we don't have an OAuth2 token, disable
                    // the XOAUTH2 authentication mechanism.
                    client.AuthenticationMechanisms.Remove("XOAUTH2");

                    // Note: only needed if the SMTP server requires authentication
                    client.Authenticate("xxx@163.com", "password");

                    client.Send(message);
                    client.Disconnect(true);
                }
            }
            catch(Exception ex)
            {

            }
        }

这里需要注意几点:

1. 需要用587端口,并且开启SSL

2. 检查邮箱设置里面是否开启   POP3/SMTP、IMAP/SMTP服务 

参考链接:

https://stackoverflow.com/questions/44305186/the-smtp-server-has-unexpectedly-disconnected-in-mailkit

http://www.cnblogs.com/savorboard/p/aspnetcore-email.html

原文地址:https://www.cnblogs.com/jiao006/p/7525103.html