先表明Outlook的参数:网址:https://support.office.com/zh-cn/article/Outlook-com-%E7%9A%84-POP%E3%80%81IMAP-%E5%92%8C-SMTP-%E8%AE%BE%E7%BD%AE-d088b986-291d-42b8-9564-9c414e2aa040
POP 访问是被默认禁用的。 若要启用 POP 访问,请参阅在 Outlook.com 中启用 POP 访问。
IMAP 服务器名称outlook.office365.com
IMAP 端口 993
IMAP 加密方法TLS
POP 服务器名称outlook.office365.com
POP 端口 995
POP 加密方法 TLS
SMTP 服务器名称smtp.office365.com
SMTP 端口 587
SMTP 加密方法 STARTTLS
安装nuget包:因为使用的core项目,所以引用了ReturnTrue.AspNetCore.Net.SmtpClient包(SmtpClient)。
官方指定代码:
Yes, I am using SMTP client submission. This is the c# code: var smtpClient = new SmtpClient() { Host = "smtp.office365.com", Port = 587, UseDefaultCredentials = false, EnableSsl = true }; smtpClient.Credentials = new NetworkCredential("*** 发送邮箱账号 ***", "密码"); var message = new MailMessage { From = new MailAddress("*** 发送邮箱账号 ***"), Sender = new MailAddress("*** 接收邮箱账号 ***"), Subject = "Test mail", IsBodyHtml = false }; message.To.Add("*** 接收邮箱账号 ***"); message.Body = "This is a test mail. "; smtpClient.Send(message);
上述代码运行无误,因为一开始没有找到该代码,导致写的代码出现以下异常:
Message=The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.57 SMTP; Client was not authenticated to send anonymous mail during MAIL FROM [HK0P153CA0010.APCP153.PROD.OUTLOOK.COM]
源代码:这是我之前写的代码,实际上是一样的,但是一开始一直报上述错误(原因就是在绑定账号密码前要设置UseDefaultCredentials = false)
string smtpServer = "smtp.office365.com"; int smtpPort = 587; string mailFrom = "xxx@outlook.com"; string passWord = "xxxxxx"; string mailTo = "xxxx@qq.com"; SmtpClient smtpClient = new SmtpClient(smtpServer, smtpPort); smtpClient.UseDefaultCredentials = false;//写到这里不报错 smtpClient.Credentials = new NetworkCredential(mailFrom, passWord); smtpClient.EnableSsl = true; //smtpClient.UseDefaultCredentials = false;//写到这里会报错,必须在账号密码绑定前写。 MailAddress mailAddressFrom = new MailAddress(mailFrom); MailAddress mailAddressTo = new MailAddress(mailTo, "xx的QQ邮箱"); MailMessage mailMessage = new MailMessage(mailAddressFrom, mailAddressTo); mailMessage.Subject = "用c#测试发送邮件"; mailMessage.Body = "这是一次测试发送,发送人用的outlook邮箱"; mailMessage.BodyEncoding = Encoding.UTF8; smtpClient.Send(mailMessage);
代码很短,单想到实例化对象的顺序还会产生这样的结果,以后要注意了。