Search code examples
c#azuresmtpsendgrid

SendGrid SMTP integration issue


I am trying to integrate SendGrid in ASP.NET MVC application using SmtpClient and MailMessage methods on Azure.

Code:

MailMessage message = new MailMessage();
message.IsBodyHtml = true;
message.Subject = "Subject";
message.To.Add("[email protected]");
message.Body = "Body";
message.From = new MailAddress("[email protected]", "From Name");

SmtpClient client = new SmtpClient("smtp.sendgrid.net");
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential("??", "SG.******");
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.Port = 587; // I have tried with 25 and 2525
client.Timeout = 99999;
client.EnableSsl = false;

client.Send(message);

I end up with this issue both from C# console application and ASP.NET MVC application on Azure VM:

System.Net.Mail.SmtpException: Failure sending mail. ---> System.IO.IOException: Unable to read data from the transport connection: net_io_connectionclosed.

As per the documentation avlb on SendGrid site: https://sendgrid.com/docs/Classroom/Basics/Email_Infrastructure/recommended_smtp_settings.html

The UserName and Password has to : Use the string “apikey” for the SMTP username and use your API key for the password.

I have tried -

  1. SendGrid UserName with which I login to their portal

  2. The API Key from this page https://app.sendgrid.com/settings/api_keys

  3. The password which starts with SG* which is as per their support team.

Any suggestions what am I missing or what which UserName/APIKey should I be using?

Tx!


Solution

  • The link says: Use the string “apikey” for the SMTP username and your API key for the password.

    https://docs.sendgrid.com/for-developers/sending-email/v2-csharp-code-example#using-nets-built-in-smtp-library

    The username was supposed to be "apikey" and not the actual "api key or api name"

    client.Credentials = new NetworkCredential("apikey", 
                                               "<Your API Key which starts with SG.*>");
    

    Adding "apikey" (facepalm) fixed my problem.