简体   繁体   中英

Sending email via Gmail SMTP hangs indefinitely without error

In my ASP.NET MVC 5 application, I use emails ( System.Net.Mail ) primarily for account authentication. It's worked perfectly until recently, and I have no idea what happened. I didn't change anything even slightly related to emails, as far as I know.

When I try to step into the SendAsync call in the controller, it transfers control back to the browser where it hangs indefinitely. Eventually I have to stop and restart the application pool just to access any page, which takes a couple minutes (usually it can be turned back on almost instantly).

I have it set up to use a Google app password, which is a requirement (you get an error about security otherwise). It doesn't seem to even get as far as Google, since the new app password hasn't been used .

I've tried the TLS port as well as the SSL port. Last time I got it working was using TLS.

Web.config:

<configuration>
  <appSettings>
    <add key="SmtpUsername" value="email@gmail.com" />
    <add key="SmtpPassword" value="AppPassword" />
    <add key="SmtpSender" value="email@gmail.com" />
    <add key="SmtpHost" value="smtp.gmail.com" />
    <add key="SmtpPort" value="587" /> <!-- SSL: 465, TLS: 587 -->
    <add key="SmtpEnableSsl" value="true" />
  </appSettings>
</configuration>

Email code:

public class EmailClient : SmtpClient
{
    public EmailClient()
    {
        UseDefaultCredentials = false;
        Host = WebConfigurationManager.AppSettings.Get("SmtpHost");
        Port = int.Parse(WebConfigurationManager.AppSettings.Get("SmtpPort"));
        EnableSsl = bool.Parse(WebConfigurationManager.AppSettings.Get("SmtpEnableSsl"));
        Credentials = new NetworkCredential(WebConfigurationManager.AppSettings.Get("SmtpUsername"),
                                            WebConfigurationManager.AppSettings.Get("SmtpPassword"));
        DeliveryMethod = SmtpDeliveryMethod.Network;
        Timeout = 30000; // Waiting 30 seconds doesn't even end the "loading" status
    }
}

public class EmailMessage : MailMessage
{
    private bool isBodyHtml = true;

    public EmailMessage(string subject, string body, string recipients)
        : base(WebConfigurationManager.AppSettings.Get("SmtpSender"), recipients, subject, body)
    {
        IsBodyHtml = isBodyHtml;
    }

    public EmailMessage(string subject, string body, IEnumerable<string> recipients)
        : base(WebConfigurationManager.AppSettings.Get("SmtpSender"), string.Join(",", recipients), subject, body)
    {
        IsBodyHtml = isBodyHtml;
    }
}

public static class Email
{
    /// <param name="recipients">Comma-delimited list of email addresses</param>
    public static async Task SendAsync(string subject, string body, string recipients)
    {
        using (EmailMessage msg = new EmailMessage(subject, body, recipients))
        using (EmailClient client = new EmailClient())
        {
            await client.SendMailAsync(msg);
        }
    }

    /// <param name="recipients">Collection of email addresses</param>
    public static async Task SendAsync(string subject, string body, IEnumerable<string> recipients)
    {
        using (EmailMessage msg = new EmailMessage(subject, body, recipients))
        using (EmailClient client = new EmailClient())
        {
            await client.SendMailAsync(msg);
        }
    }
}

Usage:

public class TestController : BaseController
{
    public async Task<ActionResult> Test()
    {
        await Email.SendAsync("TEST", "test", "anaddress@gmail.com");
        return View(); // Never reaches this point
    }
}

OP here. As some answers allude, there was nothing wrong with my code. I'm not sure which of the below I had changed without retesting, but this is what you must have to use Gmail SMTP :

  • Use TLS port 587
  • Set SmtpClient.EnableSsl to true
  • Enable MFA for the Google account and use an app password for the SmtpClient.Credentials . I needed to enable MFA to create an app password.

Please note the Documentation and see the Gmail sending limits. under Gmail SMTP server section.

Your code looks fine, the only thing I see is that you are enabling SSL, but using the port distained for 'TLS' so users who will use the SSL method, will engage in an issue.

Beside from that, nothing appears to the eye.

There is standard way to send emails from ASP.NET.

web.config

  <system.net>
    <mailSettings>
      <smtp deliveryMethod="Network">
        <network defaultCredentials="false" enableSsl="true" host="smtp.gmail.com" password="password" port="587" userName="user@gmail.com"/>
      </smtp>
    </mailSettings>
  </system.net>

.cs

var smtp = new SmtpClient(); // no other code. 
var msg = CreateEmailMessage();
//I use try... catch
try{
   smtp.Send(msg);
   //return true; //if it is a separate function
}
catch(Exception ex){
   //return false; 
   //use ex.Message (or deeper) to send extra information
}

Note that Gmail doesn't except a sender other than username . If you want your addressee to answer to another address then use

msg.ReplyToList.Add(new MailAddress(email, publicName));

This is much more easier. Make sure to add the relevant name spaces. Keep in mind that this is done using gmail smtp address. it changes from email provider to email provider. This code works perfectly for me..

using System.IO;
using System.Net.Mail;
using System.Net;

public void sendmail()
{
    string emailFrom = "SENDING GMAIL ADDRESS HERE";
    string subject = " SUBJECT HERE";
    string body = "MESSAGE BODY HERE";
    MailMessage maile = new MailMessage(emailFrom, "RECIEVERS EMAIL ADDRESS", subject, body);
    SmtpClient client = new SmtpClient("smtp.gmail.com",587);
    client.Credentials = new System.Net.NetworkCredential("SENDING GMAIL ADDRESS HERE", "SENDERS GMAIL PASSWORD HERE");
    client.EnableSsl = true;
    try
    {
        client.Send(maile);
    }
    catch(Exception e)
    {
        MessageBox.Show("" + e);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM