2012-04-19 72 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); 
     }