System.Net.Mail.SmtpClient一般發送如果啓用了ssl則他會先從25端口去建立握手,一般郵件服務器都會禁用25端口,因此會發送報錯,遠程服務器無響應,連接超時
推薦用web方式發送郵件,這樣成功率很高,需要引用C#的程序集組件System.Web
參考代碼:
public static void SendEmail()
{
//發件人
const string sendAddress = "[email protected]";
//發件人密碼
const string sendPassword = "123456";
//收件人
const string receiveAddress = "[email protected]";
System.Web.Mail.MailMessage mail = new System.Web.Mail.MailMessage();
try
{
mail.From = sendAddress;
mail.To = receiveAddress;
mail.Subject = "whl測試發送郵件2-26-1";
mail.BodyFormat = System.Web.Mail.MailFormat.Html;
mail.Body = "whl發送的測試郵件" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1"); //basic authentication
mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", sendAddress); //set your username here 發件人郵箱
mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", sendPassword); //set your password here 發件人郵箱密碼
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
System.Web.Mail.SmtpMail.SmtpServer = "msg.petrochina.com.cn";
System.Web.Mail.SmtpMail.Send(mail);
Console.WriteLine("發送郵件成功");
}
catch (Exception ex)
{
var exg = ex.InnerException ?? ex;
string msg = exg.ToString();
Console.WriteLine(msg);
}
}
轉載:
https://blog.csdn.net/molu474305148/article/details/99713389