2012-04-19 36 views
1

儘管在Stackoverflow上有關於此的所有主題。我不能設法找到這一問題的解決方案:用C發送郵件#

我有這樣的例外:

SMTP服務器需要安全連接或客戶端是不是 authentificated。服務器的回覆是:5.5.1認證 必需。瞭解更多信息,使用此代碼

var fromAddress = new MailAddress(user.Email, "From Name"); 
    var toAddress = new MailAddress("[email protected]", "To Name"); 
    const string fromPassword = "fromPassword"; 
    const string subject = "Subject"; 
    const string body = "Body"; 

    var smtp = new SmtpClient 
    { 
     Host = "smtp.gmail.com", 
     Port = 587, 
     EnableSsl = true, 
     DeliveryMethod = SmtpDeliveryMethod.Network, 
     UseDefaultCredentials = false, 
     Credentials = new NetworkCredential(fromAddress.Address, fromPassword), 
     Timeout = 20000 
    }; 
    using (var message = new MailMessage(fromAddress, toAddress) 
    { 
     Subject = subject, 
     Body = body 
    }) 
    { 
     smtp.Send(message); 
    } 

我在想什麼嗎? 感謝您的幫助

+8

這是要求和回答在SO信息重新搜索之前,你問? – Oded 2012-04-19 13:04:58

+3

http://stackoverflow.com/questions/704636/sending-email-through-gmail-smtp-server-with-c-sharp – Prix 2012-04-19 13:05:40

+0

看看下面的內容:http://stackoverflow.com/questions/704636/sending-電子郵件通過Gmail的smtp服務器與C - 銳 – Tomtom 2012-04-19 13:06:13

回答

1

此代碼爲我工作

SmtpClient sc = new SmtpClient("smtp.gmail.com"); 
    NetworkCredential nc = new NetworkCredential("username","password"); 
    //username doesn't include @gmail.com   
    sc.UseDefaultCredentials = false; 
    sc.Credentials = nc; 
    sc.EnableSsl = true; 
    sc.Port = 587; 
    try 
     { 
     sc.Send(mm); 
     } 
    catch (Exception ex) 
     { 
     EventLog.WriteEntry("Error Sending", EventLogEntryType.Error); 
     }