使用Asp.net发送电子邮件时出现异常

本文关键字:异常 电子邮件 Asp net 使用 | 更新日期: 2023-09-27 18:28:32

我一直在尝试让一个网页使用Gmail作为smtp服务器通过Asp.net发送电子邮件。下面是谷歌为这种情况设置的设置链接。https://support.google.com/a/answer/176600?hl=en

每次我尝试发送电子邮件时,我都会收到"RetryIFBus()中捕获的异常"消息。。

有什么想法吗?。。。下面是我的代码:

    [System.Web.Services.WebMethod]
    public static void SendMessage(string toEmail)
    {
        MailMessage msg = new MailMessage("myEmail@gmail.com", toEmail);
        msg.Subject = "Email Subject";
        msg.Body = "Here goes email body";
        msg.IsBodyHtml = false;
        SmtpClient smtp = new SmtpClient("smtp.gmail.com");
        System.Net.NetworkCredential netCred = new System.Net.NetworkCredential();
        netCred.UserName = "myEmail@gmail.com";
        netCred.Password = "myPassword";
        smtp.Credentials = netCred;
        smtp.Port = 465;
        smtp.EnableSsl = true;
        try
        {
            smtp.Send(msg);
            Console.WriteLine("Email Successfully sent!!");
        }
        catch (SmtpFailedRecipientsException ex)
        {
            for (int i = 0; i < ex.InnerExceptions.Length; i++)
            {
                SmtpStatusCode status = ex.InnerExceptions[i].StatusCode;
                if (status == SmtpStatusCode.MailboxBusy ||
                    status == SmtpStatusCode.MailboxUnavailable)
                {
                    Console.WriteLine("Delivery failed - retrying in 5 seconds.");
                    System.Threading.Thread.Sleep(5000);
                    smtp.Send(msg);
                }
                else
                {
                    Console.WriteLine("Failed to deliver message to " +
                        ex.InnerExceptions[i].FailedRecipient);
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("Exception caught in RetryIfBusy(): " +
                    ex.ToString());
        }
    } 

使用Asp.net发送电子邮件时出现异常

您在Google的SMTP服务器上使用了错误的端口。应为:

smtp.Port = 587;