我写了一个应用程序,它通过电子邮件向人们发送通知。出于测试目的,我使用 Gmail 的 SMTP 服务器。使用下面的代码进行测试,但我随机得到以下错误。
我在端口 587 上使用 smtp.gmail.com
System.Net.Mail.SmtpException: The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required. Learn more at
at System.Net.Mail.MailCommand.CheckResponse(SmtpStatusCode statusCode, String response)
at System.Net.Mail.SmtpTransport.SendMail(MailAddress sender, MailAddressCollection recipients, String deliveryNotify, SmtpFailedRecipientException& exception)
at System.Net.Mail.SmtpClient.Send(MailMessage message)
at EmailAlertService.Email.sendMail(String subject, String body, String[] recipients, String from, String& error)
大约五分之一的电子邮件会生成此异常。我对每个测试都使用相同的凭据和往返地址组合。知道是我在做什么,还是 Gmail 服务器出现问题!
public bool sendMail(string subject, string body, string[] recipients, string from, ref string error)
{
bool success = recipients != null && recipients.Length > 0;
if (success)
{
SmtpClient smtpClient = new SmtpClient
{
Host = hostName,
Port = port,
EnableSsl = true,
UseDefaultCredentials = false,
Credentials = new System.Net.NetworkCredential(username, password)
};
using (MailMessage gMessage = new MailMessage(from, recipients[0], subject, body))
{
Console.WriteLine(recipients[0]);
for (int i = 1; i < recipients.Length; i++)
{
Console.WriteLine(recipients[i]);
gMessage.To.Add(recipients[i]);
}
try
{
smtpClient.Send(gMessage);
success = true;
error = string.Empty;
}
catch (Exception ex)
{
success = false;
error = ex.ToString();
}
}
}
else
error = "No destination email addresses supplied";
return success;
}