SendGrid无法通过Azure应用服务运行

SendGrid无法通过Azure应用服务运行

本文介绍了SendGrid无法通过Azure应用服务运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用最新的SendGrid .NET软件包(8.0.3)从ASP.NET Core Web应用程序发送电子邮件:

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());
}

它在本地工作,但是在Azure App Service实例上运行,邮件没有通过.

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

  • 我没有引用Microsoft.Azure.WebJobs.Extensions.SendGrid.解决方案是从Nuget添加它
  • 我没有等待异步发送完成.将.Wait()添加到发送电子邮件的异步函数中.我用于的完整代码program.cs如下:

  • I hadn't referenced Microsoft.Azure.WebJobs.Extensions.SendGrid. The solution to this is to add it from Nuget
  • 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 forprogram.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());

}

所以我建议您将.Wait()添加到函数调用中:

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();
}

这篇关于SendGrid无法通过Azure应用服务运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 11:07