用C#发送邮件

时间:2012-04-19 13:02:32

标签: c# .net email

尽管Stackoverflow上有关于此的所有主题。我无法找到解决这个问题的方法:

我有这个例外:

  

SMTP服务器需要安全连接,否则客户端不需要   authentificated。来自服务器的回复是:5.5.1认证   需要。

了解更多信息

使用此代码:

    var fromAddress = new MailAddress(user.Email, "From Name");
    var toAddress = new MailAddress("myadress@gmail.com", "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);
    }

我缺少什么? 谢谢你的帮助

3 个答案:

答案 0 :(得分:1)

你没有遗漏任何东西。我怀疑你的密码错了。你没有忘记将它从“fromPassword”改为你真正应该做的事情吗?

This is a cleaner implementation of the same task

答案 1 :(得分: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);
      }

答案 2 :(得分:1)

您启用了Google 2-Step Authentication

后,您输入的密码不正确,或者(更有可能)您尝试使用普通密码

您需要生成并使用application specific password