2013-09-24 324 views
7

這對你來說可能是非常微不足道的,但我無法弄清楚爲什麼當我運行我的代碼時出現此錯誤消息。我在同一個網站上查看了一些相關的問題,例如Sending email through Gmail SMTP server with C# 但他們都沒有幫助。任何人願意幫忙嗎? 使用不同的組件也是可以接受的。所以如果有人得到一個工作解決方案,將不勝感激。通過SMTP客戶端發送電子郵件時出錯

錯誤消息= SMTP服務器需要安全連接或客戶端未通過身份驗證。服務器響應是:5.5.1需要身份驗證。瞭解更多

這裏是我的代碼

System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();  
message.From = new MailAddress("[email protected]"); 
message.To.Add("[email protected]"); 
message.Subject = "Hello"; 
message.Body = "Hello Bob "; 
message.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure; 

SmtpClient smtpClient = new SmtpClient("smtp.gmail.com", 587); 
smtpClient.EnableSsl = true; 
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network; 
smtpClient.UseDefaultCredentials = false; 
smtpClient.Credentials = new NetworkCredential("MyGoogleMailAccount", 
               "mygooglemailpassword"); 

smtpClient.Send(message.From.ToString(), message.To.ToString(), 
       message.Subject, message.Body); 
+1

From = Hotmail? – Steve

+0

Duplicate http://stackoverflow.com/questions/704636/sending-email-through-gmail-smtp-server-with-c-sharp – Pete

+1

順便說一句,如果您使用Hotmail的地址,gmail可能會抱怨。 – Pete

回答

10

我不認爲有什麼不妥比E-mail地址等你的代碼。我用這段代碼成功地將一封電子郵件從gmail發送到我的個人帳戶(實際上在LINQPad中運行它)。只需用您帳戶的有效值替換3個字符串值,您應該很好地去:

MailMessage message = new System.Net.Mail.MailMessage(); 
string fromEmail = "[email protected]"; 
string fromPW = "mypw"; 
string toEmail = "[email protected]"; 
message.From = new MailAddress(fromEmail); 
message.To.Add(toEmail); 
message.Subject = "Hello"; 
message.Body = "Hello Bob "; 
message.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure; 

using(SmtpClient smtpClient = new SmtpClient("smtp.gmail.com", 587)) 
{ 
    smtpClient.EnableSsl = true; 
    smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network; 
    smtpClient.UseDefaultCredentials = false; 
    smtpClient.Credentials = new NetworkCredential(fromEmail, fromPW); 

    smtpClient.Send(message.From.ToString(), message.To.ToString(), 
        message.Subject, message.Body); 
} 
+0

嗨皮特。我認爲這可能是一些防火牆問題或與我的谷歌郵箱用戶名和密碼。 – Sike12

+0

你確定你正在使用正確的帳戶和密碼?我想如果它被防火牆阻止,你將不會得到迴應。 – Pete

+0

嘗試使用端口465代替 – Pete

0

通過this post.

MailMessage mail = new MailMessage("[email protected]", "[email protected]"); 
SmtpClient client = new SmtpClient(); 
client.Port = 25; 
client.DeliveryMethod = SmtpDeliveryMethod.Network; 
client.UseDefaultCredentials = false; 
client.Host = "smtp.google.com"; 
mail.Subject = "this is a test email."; 
mail.Body = "this is my test email body"; 
client.Send(mail); 
+4

如果將其更改爲smtp.gmail.com(使用Googlemail憑據),則會報告一條顯示「{」遠程名稱無法解析的錯誤消息:'smtp.google.com'「} – Sike12

+0

)或smtp.live.com(與hotmail憑據),那麼這將工作正常:) – Sike12

相關問題