Reputation: 5503
I am using the latest SendGrid .NET package (8.0.3) to send e-mails from my ASP.NET Core web app:
public Task SendEmailAsync(string email, string subject, string message)
{
return Send(email, subject, message);
}
async Task Send(string email, string subject, string message)
{
dynamic sg = new SendGridAPIClient(_apiKey);
var from = new Email("[email protected]", "My Name");
var to = new Email(email);
var content = new Content("text/html", message);
var mail = new Mail(from, subject, to, content);
await sg.client.mail.send.post(requestBody: mail.Get());
}
It works locally, but running on an Azure App Service instance the mails don't come through.
The code runs fine without any exceptions so I have little to work with, but I am thinking it could be some sort of firewall issue.
Has anyone experienced similar issues? How do I go about to debug this?
Upvotes: 9
Views: 7787
Reputation: 63
Although the question is old I'm providing an answer as I came across a similar issue and couldn't find any clear solutions. The reason why it wasn't working for me was because
I wasn't waiting for the async send to complete. Add .Wait() to the async function that sends the email. The full code I used for program.cs is below:
static void Main()
{
var config = new JobHostConfiguration();
if (config.IsDevelopment)
{
config.UseDevelopmentSettings();
}
config.UseSendGrid();
//The function below has to wait in order for the email to be sent
SendEmail(*Your SendGrid API key*).Wait();
}
public static async Task SendEmail(string key)
{
dynamic sg = new SendGridAPIClient(key);
Email from = new Email("[email protected]");
string subject = "Test";
Email to = new Email("[email protected]");
Content content = new Content("text/html", "CONTENT HERE");
Mail mail = new Mail(from, subject, to, content);
dynamic s = await sg.client.mail.send.post(requestBody: mail.Get());
}
So I would suggest you add .Wait() to your function call:
public Task SendEmailAsync(string email, string subject, string message)
{
//Added .Wait()
return Send(email, subject, message).Wait();
}
Upvotes: 3
Reputation: 2414
I had the same issue and the problem for me was that I had the SendGrid apiKey stored as an environment variable in the project which worked local host but not once api was hosted on azure.
Upvotes: 1
Reputation: 134
I use SendGrid in my Azure Web App as well. I can send when debugging locally AND after deployed to production in Azure. Here are a couple of things to check:
Upvotes: 0