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("noreply@my.domain", "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?
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("from@domain.com"); string subject = "Test"; Email to = new Email("to@domain.com"); 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();
}
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:
我有同样的问题,对我来说问题是我将SendGrid apiKey存储为项目中的环境变量,该项目使用本地主机但不是一次api托管在azure上。
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.