2013-04-04 73 views
0

嗨,我正在嘗試使用Gmail憑證和調用電子郵件模板發送一封電子郵件,但它拋出一個異常發送郵件失敗發送與使用Gmail憑證

SmtpClient SmtpServer = new SmtpClient(); 
SmtpServer.Credentials = new System.Net.NetworkCredential("[email protected]", "xxxxxx"); 
SmtpServer.Port = 587; 
SmtpServer.Host = "smtp.gmail.com"; 
SmtpServer.EnableSsl = true; 
message = new MailMessage(); 
message.Subject = "Visitor Arrived"; 
message.SubjectEncoding = System.Text.Encoding.UTF8; 
message.IsBodyHtml = false; 
message.Body = "EmailTemplate.html"; 
message.BodyEncoding = System.Text.Encoding.UTF8; 
message.From = new MailAddress("[email protected]"); 
message.To.Add(lblCPEmail.Text); 
message.Priority = MailPriority.High; 
message.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure; 
SmtpServer.Send(message); 

請幫我出模板電子郵件。

回答

0

你必須使用StreamReader從HTML文件中讀取....,也是MailMessage.BodyFormat屬性設置爲MailFormat.Html
使用:

SmtpClient SmtpServer = new SmtpClient(); 
SmtpServer.Credentials = new System.Net.NetworkCredential("[email protected]", "xxxxxx"); 
SmtpServer.Port = 587; 
SmtpServer.Host = "smtp.gmail.com"; 
SmtpServer.EnableSsl = true; 

using (StreamReader reader = File.OpenText(htmlFilePath)) // Path to your 
{               // HTML file 
    message = new MailMessage(); 
    message.Subject = "Visitor Arrived"; 
    message.SubjectEncoding = System.Text.Encoding.UTF8; 
    message.IsBodyHtml = false; 
    message.BodyEncoding = System.Text.Encoding.UTF8; 
    message.From = new MailAddress("[email protected]"); 
    message.To.Add(lblCPEmail.Text); 
    message.Priority = MailPriority.High; 

    message.Body = reader.ReadToEnd(); // Load the content from your file... 
    //... 
} 
SmtpServer.Send(message); 

回答Send a email with a HTML file as body (C#)

0
  foreach (GnrDataMailInfo dmi in lstDMI) 
      { 
       MailMessage mail = new MailMessage(); 
       mail.From = "youremail"; 

       SmtpClient smtp = new SmtpClient(); 
       smtp.Port = 25; // [1] port 
       smtp.EnableSsl = true; 
       smtp.DeliveryMethod = SmtpDeliveryMethod.Network; // [2] Added this 
       smtp.UseDefaultCredentials = false; // [3] Changed this 
       smtp.Credentials = new NetworkCredential(mail.From.ToString(), "password"); // [4] Added this. 
       smtp.EnableSsl = false; 
       smtp.Timeout = 20000; 
       smtp.Host = "yourhost"; 

       mail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure; 
       mail.BodyEncoding = System.Text.Encoding.UTF8; 
       mail.HeadersEncoding = System.Text.Encoding.UTF8; 
       mail.Subject = dmi.Subject; 
       mail.To.Add(dmi.To); 
       mail.IsBodyHtml = true; 
       mail.Body = dmi.Body; 

       smtp.Send(mail); 
      } 
+0

歡迎來到SO。它有助於解釋爲什麼你的答案是正確的,而不是隻發佈代碼。 – 2016-11-03 07:52:16

0

部分取使用端口465代替

端口465用於smtps SSL加密在任何SMTP級別通信之前自動啓動。

端口587用於msa 它幾乎就像標準的SMTP端口。 MSA應在驗證後接受電子郵件(例如,在SMTP AUTH之後)。當DUL範圍的網絡管理員可以阻止到SMTP端口(端口25)的傳出連接時,它有助於阻止傳出的垃圾郵件。