2012-03-29 133 views
0

可能重複:
Sending email in .NET through Gmail.NET通過Gmail發送郵件

我試圖通過Gmail的賬戶我已經創建發送與Asp.Net(MVC3)郵件。我已經抓取了互聯網的方法,但我沒有嘗試過一直工作。

我有一個看起來像這樣

public static bool SendEmail(string to,string subject,string body) 
    { 
     try 
     { 
      MailMessage mail = new MailMessage(); 
      mail.From = new MailAddress("[email protected]"); 
      mail.To.Add(to); 
      mail.Subject = subject; 
      mail.Body = body; 
      mail.IsBodyHtml = false; 

      SmtpClient smtp = new SmtpClient(); 
      smtp.DeliveryMethod = SmtpDeliveryMethod.Network; 
      smtp.Host = "smtp.gmail.com"; 
      smtp.Port = 587; 
      smtp.Credentials = new System.Net.NetworkCredential("[email protected]", "mypassword"); 
      smtp.EnableSsl = true; 
      smtp.Send(mail); 
      return true; 
     } 
     catch 
     { 
      return false; 
     } 
    } 

這種方法使用它時,即時返回false的方法。我該如何解決這個問題?

+3

請告訴我的錯誤? – 2012-03-29 18:39:47

+3

替換catch(異常e),然後放置一個斷點並查看它是什麼錯誤 – Shyju 2012-03-29 18:40:35

+0

您的(和/或webapp的)防火牆上是否打開出站端口587? – 2012-03-29 18:48:09

回答

2

我覈實了以下工作:

static void Main(string[] args) 
{ 
    //create the mail message 
    MailMessage mail = new MailMessage(); 

    var client = new SmtpClient("smtp.gmail.com", 587) 
    { 
     Credentials = new NetworkCredential("[email protected]", "yourpassword"), 
     EnableSsl = true 
    }; 

    //set the addresses 
    mail.From = new MailAddress("[email protected]"); 
    mail.To.Add("[email protected]"); 

    //set the content 
    mail.Subject = "Test subject!"; 
    mail.Body = "<html><body>your content</body></html>"; 
    mail.IsBodyHtml = true; 
    client.Send(mail); 
} 
0

嘗試添加該行

smtp.UseDefaultCredentials = false;