C# SMTP 邮件发送之QQ邮箱篇

来源:互联网 发布:nginx 1.8.0 编辑:程序博客网 时间:2024/06/05 11:02

邮件发送大家都已经非常熟悉了,微软自带的System.Net.Mail也很好用,那为什么还要说呢?


QQ邮箱的SMTP以前是非SSL,用未加密的25端口,后来发送都改成SSL了,端口为465或587(实测587是连不上的)。网上查到System.Net.Mail支持Explicit SSL,但是不支持Implicit SSL。简单来说,就是System.Net.Mail不能支持像QQ邮箱这样的加密的SSL,所以我们得改一下,可以用System.Web.Mail这个比较旧的类。


虽然是过时了,但是还是可以完成我们的需求。这里登陆密码要注意:如果是一般账号,要用授权码(下面会说明设置);企业账号用登录密码,代码如下:

        System.Web.Mail.MailMessage mail = new System.Web.Mail.MailMessage();        try        {            mail.To = "接收的邮箱";            mail.From = "发送的邮箱";            mail.Subject = "这是主题";            mail.BodyFormat = System.Web.Mail.MailFormat.Html;            mail.Body = "这是内容";            mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1"); //身份验证            mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", mail.From); //邮箱登录账号,这里跟前面的发送账号一样就行            mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", "********"); //这个密码要注意:如果是一般账号,要用授权码;企业账号用登录密码            mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserverport", 465);//端口            mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpusessl", "true");//SSL加密            System.Web.Mail.SmtpMail.SmtpServer = "smtp.qq.com";    //企业账号用smtp.exmail.qq.com            System.Web.Mail.SmtpMail.Send(mail);            //邮件发送成功        }        catch (Exception ex)        {            //失败,错误信息:ex.Message;        }


QQ邮箱要设置一下:



如果是普通账号,要生成授权码:


1 0