FluentEmail icon indicating copy to clipboard operation
FluentEmail copied to clipboard

STMP gmail error

Open rafalschmidt97 opened this issue 6 years ago • 1 comments

Hi, I'm getting error while sending email:

System.Net.Mail.SmtpException: The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.0 Must issue a STARTTLS command first. q3sm3460511lff.23 - gsmtp

I've found many solution to change EnableSsl = true but IFluentEmail or ISender doesn't provide that option. What should i do to use gmail as a provider?

Here is example implementation with SmtpClient:

using (var message = new MailMessage())
{
    message.To.Add(new MailAddress("[email protected]", "To Name"));
    message.From = new MailAddress("[email protected]", "From Name");
    message.CC.Add(new MailAddress("[email protected]", "CC Name"));
    message.Bcc.Add(new MailAddress("[email protected]", "BCC Name"));
    message.Subject = "Subject";
    message.Body = "Body";
    message.IsBodyHtml = true;

    using (var client = new SmtpClient("smtp.gmail.com"))
    {
        client.Port = 587;
        client.Credentials = new NetworkCredential("[email protected]", "password");
        client.EnableSsl = true; // THIS PART IS PROBABLY IMPORTANT 💩
        client.Send(message);
    }
}

Edit: EnableSsl solves the problem. How can I change this parameter with this library?

Edit2:

Here is what I did to make it working. I was desperate 😅

public static class EmailExtension
  {
    public static void AddEmail(this IServiceCollection services, IConfiguration configuration)
    {
      services
        .AddFluentEmail(configuration["Email:Username"], configuration["Email:Name"])
        .AddSmtpSender(PrepareSmtpClientSsl(configuration))
        .AddRazorRenderer();
    }

    private static SmtpClient PrepareSmtpClientSsl(IConfiguration configuration)
    {
      return new SmtpClient(configuration["Email:Host"], int.Parse(configuration["Email:Port"]))
      {
        EnableSsl = true,
        DeliveryMethod = SmtpDeliveryMethod.Network,
        Credentials = new NetworkCredential(configuration["Email:Username"], configuration["Email:Password"])
      };
    }
  }

Can I somehow simplify this?

rafalschmidt97 avatar Mar 25 '19 18:03 rafalschmidt97

If you load credentials from configuration - make sure you escape the strings, especially backslashes.

JTinkers avatar Oct 29 '20 10:10 JTinkers