Why are my emails sent from my ASP.Net core web app using Azure SendGrid sometimes not being received

Viewed 421

I am using Azure Sendgrid to send emails from my ASP.net core web application. Intermittently, emails are not being received by some of the recipients. Some recipients receive the email, others do not.

Code below is for brevity, not including setting up MailMessage (FROM, TO, etc...)

I am using "smtp.sendgrid.net" as smtpserver with "port" 587 as smtpport.

string smtpServer = ConfigurationManager.AppSettings["MailSMTPServer"];
   int smtpPort = int.Parse(ConfigurationManager.AppSettings["MailPort"]);
   string username = ConfigurationManager.AppSettings["MailUserName"];
   string pwd = ConfigurationManager.AppSettings["MailPassword"];


   SmtpClient client = new SmtpClient(smtpServer);

   client.Port = smtpPort;
   client.UseDefaultCredentials = false;
   client.Credentials = new NetworkCredential(username, pwd);
   client.DeliveryMethod = SmtpDeliveryMethod.Network;

   client.Send(mailMessage);

I have talked with the IT dept where emails are not being received to see if they are being blocked. There is no record of the emails hitting their server.

1 Answers

It's recommended to use their REST API over SMTP.

  • SMTP relay creates multiple points of potential failure, meaning that there are more places in the conversation between the sender and SendGrid that could cause one of those “not okay” messages.
  • The Web API is faster. The extra back and forth necessary in SMTP relay can cause some (minimal) latency for customers who are outside of the United States, and thus further from our inbound data centers.
  • The Web API also allows you to add an extra layer of security to your program by utilizing API keys. API keys allow you to generate an authentication credential separate from your username password, which significantly lowers the chance of someone using your account to send spam or phish.

Also, there might be whitelisting issue due to outbound SMTP restriction in Azure. If you use REST API instead, you can overcome that.

Here is a C# example using their nuget.

var apiKey = "<send grid api key>";
var client = new SendGridClient(apiKey);
var from = new EmailAddress("test@example.com", "Example User");
var subject = "Sending with SendGrid is Fun";
var to = new EmailAddress("test@example.com", "Example User");
var plainTextContent = "and easy to do anywhere, even with C#";
var htmlContent = "<strong>and easy to do anywhere, even with C#</strong>";
var msg = MailHelper.CreateSingleEmail(from, to, subject, plainTextContent, htmlContent);
var response = await client.SendEmailAsync(msg);
Related