2013-07-22 259 views
1

我是C#的新手,我試圖從我正在開發的桌面程序發送電子郵件。下面是我使用的代碼,但我不斷收到以下錯誤:無法連接到遠程服務器

System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage(); 
message.To.Add("[email protected]"); 
message.Subject = "This is the Subject line"; 
message.From = new System.Net.Mail.MailAddress("[email protected]"); 
message.Body = "This is the message body"; 
System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient("smtp.gmail.com",578); 
smtp.EnableSsl = true; 
smtp.Send(message); 

我似乎無法找出問題是什麼...

+1

有什麼異常?或者是什麼問題? – wudzik

回答

2

缺少憑據最有可能的:

smtp.Credentials = new System.Net.NetworkCredential("[email protected]", "password"); 

所以:

SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587); 
smtp.Credentials = new System.Net.NetworkCredential("[email protected]", "Password"); 
smtp.EnableSsl = true; 
smtp.Send(message); 

或者,你可以存儲(幾乎所有)這個東西在app.config,雖然我不知道你如何安全的需要它,因爲用戶名/密碼將是打開的應用程序的任何用戶清晰可見目錄(和那個文件)。對於完成的緣故:

<system.net> 
    <mailSettings> 
    <smtp from="[email protected]"> 
     <network host="smtp.gmail.com" 
       enableSsl="true" 
       userName="[email protected]" 
       password="password" 
       port="587" /> 
    </smtp> 
    </mailSettings> 
</system.net> 
1

網絡憑據是非常重要的,但有時我們需要檢查端口587被阻止。

SmtpClient client = new SmtpClient(); 
    client.Credentials = new System.Net.NetworkCredential("[email protected]", "whocaresdupe"); 
    client.Port = 587; 
    client.Host = "smtp.gmail.com"; 
    client.EnableSsl = true; 
    try 
    { 
     client.Send(mail);   
    } catch (Exception ex) 
    { 
     Page.RegisterStartupScript("UserMsg", "<script>alert('Successfully Send...');if(alert){ window.location='SendEmail.aspx';}</script>"); 
    } 
+1

這是如何直接檢查端口是否打開? – Pythoner1234

0

我的公司使用McAfee中的設置阻止桌面/筆記本電腦發送電子郵件。檢查Windows事件視圖以查看是否存在阻止電子郵件的條目。

相關問題