2013-04-13 168 views
1

我想用C#發送一封電子郵件,而且我遇到了一些問題。每當我嘗試發送電子郵件時,都會收到一條消息「錯誤:無法發送郵件」。 這裏是我的代碼:C#發送電子郵件問題

try 
     { 
      client.Host = "smtp.gmail.com"; 
      client.Port = 465; 
      client.UseDefaultCredentials = false; 
      client.Credentials = smtpCreds; 
      client.EnableSsl = true; 

      MailAddress sendFrom = new MailAddress("[email protected]"); 
      MailAddress sendTo = new MailAddress("[email protected]"); 
      MailMessage msg = new MailMessage(sendFrom,sendTo); 
      msg.Subject = "Subject"; 
      msg.Body = "Body"; 
      client.Send(msg); 
     } 
     catch (Exception e) 
     { 
      MessageBox.Show("Error:" + e.Message); 
     } 

我也有這樣的聲明:

public SmtpClient client = new SmtpClient(); 
    public System.Net.NetworkCredential smtpCreds = new System.Net.NetworkCredential("mail", "password"); 

希望你能幫助我。

+0

您是否嘗試過使用'端口= 587' – Sachin

+0

哪裏是通行證? – KF2

+0

@Sachin我有。仍然不起作用 – Stormel

回答

1

你可以試試這個,並確保使用有效的登錄證書,你有互聯網連接:

MailMessage mail = new MailMessage(); 
mail.Subject = "Your Subject"; 
mail.From = new MailAddress("senderMailAddress"); 
mail.To.Add("ReceiverMailAddress"); 
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("SenderMailAddress","SenderPassword"); 
smtp.Credentials = netCre; 

try 
    { 
    smtp.Send(mail);     
    } 
    catch (Exception ex) 
    {    
    } 
+0

不起作用。至少對我來說。 – Stormel

+0

您收到的錯誤是什麼,請解釋 – Arshad

+0

我沒有收到任何錯誤。它只是不發送郵件。 – Stormel

1

試試這個代碼

 using System.Net.Mail; 

     MailMessage mail = new MailMessage(); 
     SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com"); 
     mail.From = new MailAddress("[email protected]"); 
     mail.To.Add("[email protected]"); 
     mail.Subject = ("e mail subject"); 
     mail.Body = ("message body"); 
     SmtpServer.Port = 587; 
     SmtpServer.Credentials = new System.Net.NetworkCredential("sender's username",   "sender's password"); 
     SmtpServer.EnableSsl = true; 
     SmtpServer.Send(mail); 
     MessageBox.Show("mail Send"); 
+0

仍然是一樣的錯誤:失敗發送消息 – Stormel

+0

你檢查了你的網絡連接嗎? –

+0

我無法看到我的互聯網連接有任何問題。我也嘗試通過不同的互聯網提供商連接。同樣的問題 – Stormel