Skip to main content
 首页 » 编程设计

C# 使用 SMTP 发送电子邮件

2024年01月13日34dyllove98

Exception :

Failure sending mail.

内部异常:

Unable to connect to the remote server.

MailMessage mail = new MailMessage(); 
mail.Subject = "Your Subject"; 
mail.From = new MailAddress("abc@gmail.com"); 
mail.To.Add("xyz@yahoo.co.in"); 
mail.Body = "Hello! your mail content goes here..."; 
mail.IsBodyHtml = true; 
 
SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587); 
smtp.EnableSsl = true; 
NetworkCredential netCre = new NetworkCredential("abc@gmail.com", "xxx"); 
smtp.Credentials = netCre; 
 
try 
{ 
     smtp.Send(mail); 
 } 
 catch (Exception ex) 
 { 
 } 

我 ping smtp.gmail.com 它工作正常。

请您参考如下方法:

MailMessage mm = new MailMessage(); 
SmtpClient smtp = new SmtpClient();  
 
mm.From = new MailAddress("From", "DisplayName", System.Text.Encoding.UTF8); 
mm.To.Add(new MailAddress("To")); 
mm.Subject = "Subject"; 
mm.Body = "Body"; 
 
mm.IsBodyHtml = true; 
smtp.Host = "smtp.gmail.com"; 
if (ccAdd != "") 
{ 
    mm.CC.Add(ccAdd); 
} 
smtp.EnableSsl = true; 
System.Net.NetworkCredential NetworkCred = new System.Net.NetworkCredential(); 
NetworkCred.UserName = "xyz@gmail.com";//gmail user name 
NetworkCred.Password = "Password";// password 
smtp.UseDefaultCredentials = true; 
smtp.Credentials = NetworkCred; 
smtp.Port = 587; //Gmail port for e-mail 465 or 587 
smtp.Send(mm); 

它会很好地工作