2016-07-20 227 views
0

由於上述錯誤,導致在client.Send(email);處發生崩潰並崩潰。四重檢查一切。System.Net.Mail.SmtpException {「發送電子郵件失敗。」}

這裏是我的代碼:

private void submit_Click(object sender, RoutedEventArgs e) 
{ 
    string from = "************@gmail.com"; 
    string to = "*******@sru.edu"; 
    string subject = "PSLM Test"; 
    string body = "PSLM Test"; 
    string server = "smtp.gmail.com"; 
    int port = 465; 
    string username = "************"; 
    string password = "*******"; 

    SmtpClient client = new SmtpClient(server, port); 
    client.Credentials = new NetworkCredential(username, password); 

    MailMessage email = new MailMessage(from, to, subject, body); 

    email.Attachments.Add(new Attachment(GlobalVariables.attachedFilePath)); 
    email.Attachments.Add(new Attachment(GlobalVariables.formsAndTemplatesPath[0])); 
    email.Attachments.Add(new Attachment(GlobalVariables.formsAndTemplatesPath[1])); 
    email.Attachments.Add(new Attachment(GlobalVariables.formsAndTemplatesPath[2])); 

    client.Send(email); 
} 

什麼我做錯了嗎?

+2

什麼是底層錯誤?檢查你捕獲異常的'InnerException'屬性。 – lorond

+0

_總是檢查['InnerException'屬性](https://msdn.microsoft.com/en-us/library/windows/apps/system.exception.innerexception)。 –

+0

我怕這不是我們可以簡單地指出你的代碼中的錯誤,它將與你的郵件服務器的設置有關。您是否檢查過'InnerException',其中可能包含有關實際問題的更多詳細信息 – Jamiec

回答

3

Gmail SMTP端口是587而不是465.您還需要將SmtpClient.EnableSsl屬性設置爲true

client.EnableSsl = true; 

這是可能,你可能需要設置client.UseDefaultCredentialsfalse設置新的網絡憑據之前。但情況並非總是如此 - 我所知道的是,當其他選項耗盡時,這往往會奏效。

client.UseDefaultCredentials = false; 
client.Credentials = new NetworkCredential(username, password); 

由於您使用的是Gmail,因此您需要在您的Google帳戶安全設置中允許安全性較低的應用。如果您使用雙因素身份驗證,則還需要創建特定於應用程序的密碼,並在代碼中使用該密碼。

+1

這樣做!它像一個魅力一樣工作!非常感謝! @ user1666620我的贊成票將不會公開,直到我有15名聲望,但我絕對投票給你! – Shaheer

-1
SmtpClient client= new SmtpClient(server, port); 

    client.Credentials = new System.Net.NetworkCredential(username, password); 
    client.UseDefaultCredentials = true; 
    client.DeliveryMethod = SmtpDeliveryMethod.Network; 
    client.EnableSsl = true; 

    MailMessage email = new MailMessage(from, to, subject, body); 

    email.Attachments.Add(new Attachment(GlobalVariables.attachedFilePath)); 
    email.Attachments.Add(new Attachment(GlobalVariables.formsAndTemplatesPath[0])); 
    email.Attachments.Add(new Attachment(GlobalVariables.formsAndTemplatesPath[1])); 
    email.Attachments.Add(new Attachment(GlobalVariables.formsAndTemplatesPath[2])); 

    client.Send(email); 
+1

這是一個不好的答案 - 它不能解釋爲什麼OP代碼不正確,或者指出做了哪些改進。實際上它也行不通。 – user1666620

+0

你怎麼說這是不好的答案? – abaravindan

+1

我在上面的評論中解釋過。你所做的只是發佈一些代碼,解釋你做了什麼改變或爲什麼,或者你的代碼更好。 – user1666620

相關問題