我正在使用最新的SendGrid .NET软件包(8.0.3)从我的ASP.NET核心Web应用程序发送电子邮件:
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());
}
它在本地运行,但在Azure App Service实例上运行时,邮件无法通过。
代码运行良好,没有任何异常,所以我几乎无法使用,但我认为它可能是某种防火墙问题。
有没有人遇到过类似的问题?我该如何调试呢?
答案 0 :(得分:1)
虽然这个问题很老,但我提供了一个答案,因为我遇到了类似的问题,但找不到任何明确的解决方案。它不适合我的原因是因为
我没有等待异步发送完成。将.Wait()添加到发送电子邮件的异步函数中。我用过的完整代码 program.cs如下:
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());
}
所以我建议你在你的函数调用中添加.Wait():
public Task SendEmailAsync(string email, string subject, string message)
{
//Added .Wait()
return Send(email, subject, message).Wait();
}
答案 1 :(得分:0)
我也在Azure Web App中使用SendGrid。我可以在本地调试时发送,也可以在Azure中部署到生产后发送。以下是一些要检查的事项:
答案 2 :(得分:0)
我遇到了同样的问题,问题在于我将SendGrid apiKey作为环境变量存储在项目中,该项目使用本地主机,但不是一次api托管在azure上。