1.获取QQ邮箱的授权码
打开QQ邮箱 - 设置 - 账户 - 开启POP3/SMTP服务 -> 根据操作获取授权码
2.设置并发送邮件——方法1
(两种配置方式)
-1:配置Web.config,在<configuration>标签中添加以下代码
(aaaaaaaaaa:表示发信人的邮箱号.
bbbbbbbbbb:表示前面获取的授权码.
端口号port:我测试25能发,而465不能发(不知道为什么).)
<system.net> <mailSettings> <smtp deliveryMethod="Network" from="nekorz <[email protected]>"> <network host="smtp.qq.com" userName="[email protected]" password="bbbbbbbbbb" port="25" enableSsl="true" /> </smtp> </mailSettings> </system.net>
-2:添加发送邮件代码
(昵称:可有可无)
MailMessage myMessage = new MailMessage(); myMessage.Subject = "Test Message"; myMessage.Body = "这是一封测试邮件."; myMessage.To.Add(new MailAddress("[email protected]", "昵称")); SmtpClient mySmtpClient = new SmtpClient(); try { mySmtpClient.Send(myMessage); } catch (SmtpException ex) { }
3.设置并发送邮件——方法2
(仅是把在Web.config中的配置,转移到了代码中)
MailMessage myMessage = new MailMessage(); myMessage.Subject = "Test Message"; myMessage.Body = "这是一封测试邮件"; myMessage.From = new MailAddress("[email protected]", "昵称"); myMessage.To.Add(new MailAddress("[email protected]", "昵称")); SmtpClient mySmtpClient = new SmtpClient(); mySmtpClient.Host = "smtp.qq.com"; mySmtpClient.Port = 25; mySmtpClient.Credentials = new System.Net.NetworkCredential("[email protected]", "bbbbbbbbbb"); //指定 SmtpClient 使用安全套接字层(SSL)加密连接 mySmtpClient.EnableSsl = true; try { mySmtpClient.Send(myMessage); } catch (SmtpException ex) { }
4.证书无法验证解决方法
在发送邮件代码前,添加证书处理代码
//设置证书处理——忽视证书问题,直接返回true ServicePointManager.ServerCertificateValidationCallback = delegate (Object obj, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { return true; };
请发表评论