8

这对您来说可能非常微不足道,但我只是无法弄清楚为什么在运行代码时会收到此错误消息。我在同一个网站上查看了一些相关问题,例如 使用 C# 通过 Gmail SMTP 服务器发送电子邮件, 但没有一个有帮助。请问有人愿意帮忙吗?使用不同的组件也是可以接受的。因此,如果有人得到一个可行的解决方案,将不胜感激。

错误消息 = SMTP 服务器需要安全连接或客户端未通过身份验证。服务器响应为:5.5.1 需要身份验证。了解更多信息

这是我的代码

System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();      
message.From = new MailAddress("bob@googlemail.com");
message.To.Add("bob@hotmail.com");
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);   
4

2 回答 2

10

除了电子邮件地址之外,我认为您的代码没有任何问题。我使用此代码成功地将一封电子邮件从 gmail 发送到我的个人帐户(实际上是在 LINQPad 中运行它)。只需将 3 个字符串值替换为您帐户的有效值,您就可以开始了:

MailMessage message = new System.Net.Mail.MailMessage(); 
string fromEmail = "myaddr@gmail.com";
string fromPW = "mypw";
string toEmail = "recipient@receiver.com";
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);   
}
于 2013-09-24T18:11:21.867 回答
0

通过这篇文章。

MailMessage mail = new MailMessage("you@yourcompany.com", "user@hotmail.com");
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);
于 2013-09-24T17:52:43.357 回答