使用Gmails SMTP服务器发送电子邮件问题

时间:2013-06-22 14:52:59

标签: c# email smtp gmail

我写了一个通过电子邮件向人们发送通知的应用程序。出于测试目的,我使用Gmails 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)

大约五分之一的电子邮件会产生此异常。 我正在使用相同的凭据和来自地址组合的每个测试。 任何想法,如果它正在做什么或是Gmails服务器投掷合适!

   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;
    }

0 个答案:

没有答案