2013-04-04 74 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)的传出连接时,它有助于阻止传出的垃圾邮件。