今天在弄企业邮箱推送的东西,原版代码是这样的
public void SendEmail(string title, string content) { try { MailMessage mailMsg = new MailMessage(); mailMsg.To.Add(new MailAddress(ToEmails)); mailMsg.From = new MailAddress(FromEmail); // 邮件主题 mailMsg.Subject = title; // 邮件正文内容 mailMsg.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(content, null, MediaTypeNames.Text.Html)); // 添加附件 //string file = "D:\\1.txt"; //Attachment data = new Attachment(file, MediaTypeNames.Application.Octet); //mailMsg.Attachments.Add(data); //邮件推送的SMTP地址和端口 SmtpClient smtpClient = new SmtpClient(EmailHost, EmailPort); //SmtpClient smtpClient = new SmtpClient(EmailHost); // 使用SMTP用户名和密码进行验证 System.Net.NetworkCredential credentials = new System.Net.NetworkCredential(FromEmail, FromEmailPW); smtpClient.EnableSsl = true; //smtpClient.Timeout = 10000;//超时 smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network; smtpClient.UseDefaultCredentials = false; smtpClient.Credentials = credentials; smtpClient.Send(mailMsg); } catch (Exception ex) { throw; } }
按照腾讯企业邮箱给的文档,我设置好邮箱账号、密码、smtp服务器、端口号之后开始测试,发现总是报错,当时腾讯企业邮箱的官方提示是这样的
可以看到,这里给的端口号是465,(这里不知道要不要骂娘了)
然后我断断续续的测试了一下午,发现怎么都发不出邮件,按理不会啊,就这么几行代码的事情,于是我试着删除一些配置,让程序按照自己的默认值来运行,于是我删除了端口号的配置,代码如下:
/// <summary> /// /// </summary> /// <param name="UserName"></param> /// <param name="Money"></param> public void SendEmail(string title, string content) { try { MailMessage mailMsg = new MailMessage(); mailMsg.To.Add(new MailAddress(ToEmails)); mailMsg.From = new MailAddress(FromEmail); // 邮件主题 mailMsg.Subject = title; // 邮件正文内容 mailMsg.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(content, null, MediaTypeNames.Text.Html)); // 添加附件 //string file = "D:\\1.txt"; //Attachment data = new Attachment(file, MediaTypeNames.Application.Octet); //mailMsg.Attachments.Add(data); //邮件推送的SMTP地址和端口 //SmtpClient smtpClient = new SmtpClient(EmailHost, EmailPort); SmtpClient smtpClient = new SmtpClient(EmailHost); // 使用SMTP用户名和密码进行验证 System.Net.NetworkCredential credentials = new System.Net.NetworkCredential(FromEmail, FromEmailPW); smtpClient.EnableSsl = true; //smtpClient.Timeout = 10000;//超时 smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network; smtpClient.UseDefaultCredentials = false; smtpClient.Credentials = credentials; smtpClient.Send(mailMsg); } catch (Exception ex) { throw; } }
结果就发出去了,我是真的日了狗,邮件发送失败的提示的提示也没有具体信息,先记录一下,以后使用这些企业邮箱实现邮件推送,最好不要用他们提供的端口号,感觉只需要有发信服务器就行了。