SendGrid无法在Azure App Service中运行

时间:2016-08-20 10:56:37

标签: c# azure sendgrid asp.net-core-1.0

我正在使用最新的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实例上运行时,邮件无法通过。

代码运行良好,没有任何异常,所以我几乎无法使用,但我认为它可能是某种防火墙问题。

有没有人遇到过类似的问题?我该如何调试呢?

3 个答案:

答案 0 :(得分:1)

虽然这个问题很老,但我提供了一个答案,因为我遇到了类似的问题,但找不到任何明确的解决方案。它不适合我的原因是因为

  • 我没有引用Microsoft.Azure.WebJobs.Extensions.SendGrid。解决方案是从Nuget
  • 添加它
  • 我没有等待异步发送完成。将.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中部署到生产后发送。以下是一些要检查的事项:

  1. API密钥 - 显然需要API密钥;仔细检查你如何填充它。通常,此值通过配置设置。部署的配置值是否与本地运行时的值相同?也许你有一个web.config转换在部署期间妨碍了,或者你应该有一个覆盖设置(比如你的应用程序的应用程序设置,如果你正在使用Web App服务)。
  2. SendGrid活动&抑制 - 你检查了SendGrid的活动日志吗?问题可能是您收到SendGrid的请求,或者可能是SendGrid收到您的请求但是没有完成它。检查活动源并搜索您期望的特定电子邮件(日志可搜索并按时间排序)。如果您在此处看到与您的电子邮件对应的日志,则问题出在SendGrid端。有时候电子邮件被抑制,并且可能由于多种原因而发生(退回传递,标记为垃圾邮件,甚至您的DNS服务器无法进行域名所有权验证)。如果是这种情况,日志将提供证据。您也可以直接转到Suppressions并在那里搜索电子邮件地址。
  3. 网络可用性 - 如果您使用Web App服务托管您的应用程序(看起来就是这种情况),那么您可以假设您的Web应用程序可以发出网络请求,这显然需要点击SendGrid API或SMTP服务器。但是,如果您将应用程序部署到Azure中托管的VM,那么可能会遇到一些问题,例如防火墙。登录VM并手动确认您可以直接向SendGrid API发出网络请求。

答案 2 :(得分:0)

我遇到了同样的问题,问题在于我将SendGrid apiKey作为环境变量存储在项目中,该项目使用本地主机,但不是一次api托管在azure上。