【问题标题】:Sendgrid not sending email in an on demand azure webjob running as console applicationSendgrid 没有在作为控制台应用程序运行的按需 azure webjob 中发送电子邮件
【发布时间】:2018-02-15 05:33:00
【问题描述】:

我有一个作为控制台应用程序运行的按需 azure webjob。

目标是向客户发送电子邮件。

问题是它不发送电子邮件。

我的代码大量来自msdn 部分如何:发送电子邮件。以下是我的代码 sn-p。

class Program
{
  static void Main(string[] args)
    {
Execute(Environment.GetEnvironmentVariable("WEBJOBS_COMMAND_ARGUMENTS")).Wait();
    }

    static async Task Execute(string email)
    {
        DeserializedCustomer customer = JsonConvert.DeserializeObject<DeserializedCustomer>(email);
        var apiKey = Environment.GetEnvironmentVariable("SENDGRID_APIKEY");
        var client = new SendGridClient(apiKey);
        SendGridMessage msg = new SendGridMessage()
        {
            From = new EmailAddress(customer.Email, "From Email"),
            Subject = $"Inquiry by - {customer.FirstName} {customer.LastName}",
            PlainTextContent = customer.Comments + Environment.NewLine + $"Phone : {customer.Phone}",
        };
        msg.AddTo(new EmailAddress(ToMail, ToMailName));

        if (!String.IsNullOrWhiteSpace(customer.Attachment))
        {
            List<Attachment> attachments = new List<Attachment>()
            {
                new Attachment()
                {
                    Content = customer.Attachment,
                    Type = customer.AttachmentType,
                    Filename = customer.AttachmentFileName,
                    Disposition = "inline",
                    ContentId = customer.AttachmentFileName + Guid.NewGuid()
                }
            };
            msg.Attachments = attachments;
        }
        await client.SendEmailAsync(msg);

    }
}

搜索我发现了一个 SO post 给 sendgrid 时间在控制台应用程序中发送电子邮件的地方

增加时间也无济于事。

如果从作为控制台应用程序运行的 azure webjobs 发送电子邮件有一些奇怪之处,那么我不知道。

进一步搜索我发现this SO 帖子他们成功测试了在控制台应用程序中发送电子邮件,所以我认为它可能会有所帮助,但它没有发送电子邮件。

以上所有示例都已有一年多的历史,目前都没有工作。

我尝试使用早期版本的 SendGrid 库,但我卡在了

var transportWeb = new Web(credentials);
transportWeb.DeliverAsync(myMessage);

因为 SendGrid 库已更新。

我在 github 上找到了 this,它明确指出控制台应用程序仅适用于 transportWeb.DeliverAsync(myMessage).Wait

因此我正在尝试使用 transportWeb。

Azure 与作为控制台应用程序运行的按需 Web 作业是否合并?

谁能帮忙?

更新

在 Randy Minder 的帮助下,我将代码更新为以下内容

       static async Task Execute(string email)
    {
        try
        {

            DeserializedCustomer customer = new DeserializedCustomer();
            customer = JsonConvert.DeserializeObject<DeserializedCustomer>(email);
            Console.WriteLine(customer);
            SendGridMessage msg = new SendGridMessage();
            msg.From = new MailAddress(customer.EmailAddress, "From Email");
            msg.Subject = $"Inquiry by - {customer.FirstName} {customer.LastName}";
            msg.Text = customer.Comments + Environment.NewLine + $"Phone : {customer.Phone}";

            msg.AddTo(ToMail);

            // Create a network credentials object
            var credentials = new NetworkCredential(Environment.GetEnvironmentVariable("UserName"), Environment.GetEnvironmentVariable("Password"));

            var transportWeb = new SendGrid.Web(credentials);
            transportWeb.DeliverAsync(msg).Wait();
        }
        catch (Exception ex)
        {
            DateTime now = DateTime.Now;
            Trace.TraceError($"{now.ToLongDateString()} {now.ToLongTimeString()}" + Environment.NewLine + new ExceptionSerializer(ex));
        }
    }

我正在使用 SendGrid 6.1.0

 <package id="Sendgrid" version="6.1.0" targetFramework="net47" />

我没有遇到任何异常,我的 webjob 运行成功


[09/06/2017 17:48:42 > 1a8d37: SYS INFO] Run script 'SaSRizqTechCloudWhizEngineering.Backgr.exe' with script host - 'WindowsScriptHost'
[09/06/2017 17:48:42 > 1a8d37: SYS INFO] Status changed to Running
[09/06/2017 17:48:42 > 1a8d37: INFO] SerializedEmail - {"FirstName":"adsfkh","LastName":"adfkjladf","EmailAddress":"jamilakhtar@gmail.com","Phone":"","Comments":"lkjadf ","AttachmentType":"","AttachmentFileName":"","Attachment":null}
[09/06/2017 17:48:42 > 1a8d37: INFO] FirstName adsfkh - LastName adfkjladf - EmailAddress jamilakhtar@gmail.com - Phone  - Comments lkjadf  - Attachment  - AttachmentType -  - AttachmentFileName 
[09/06/2017 17:48:44 > 1a8d37: SYS INFO] Status changed to Success

但是我没有收到任何电子邮件

【问题讨论】:

    标签: azure email sendgrid azure-webjobs ondemand


    【解决方案1】:

    当尝试在控制台应用程序中通过 SendGrid 发送电子邮件时,您必须有所不同。这是我在控制台应用程序中使用的一种方法:

    /// <summary>
    /// Send the email async in a console app.
    /// </summary>
    public async Task SendAsync()
    {
        // Create a network credentials object
        var credentials = new NetworkCredential(azureUserName, azurePassword);
    
        // Create an Web transport for sending the email
        var transportWeb = new Web(credentials);
    
        transportWeb.DeliverAsync(this._email).Wait();
    }
    

    这是我在非控制台应用程序中使用的:

        /// <summary>
        /// Send the email async in backend or MVC code.
        /// </summary>
        public async Task SendAsync()
        {
            // Create a network credentials object
            var credentials = new NetworkCredential(azureUserName, azurePassword);
    
        // Create an Web transport for sending the email
        var transportWeb = new Web(credentials);
    
        await transportWeb.DeliverAsync(this._email).ConfigureAwait(false);
    }
    

    实际的电子邮件对象包含在this._email 中。

    【讨论】:

    • 您使用的是哪个版本的 SendGrid Nuget 包?最新版本不包含 var transportWeb = new Web(credentials); 的定义
    • 你确定 var credentials = new NetworkCredential(azureUserName, azurePassword);在天蓝色的网络作业中?最新文档建议使用 var apiKey = Environment.GetEnvironmentVariable("SENDGRID_APIKEY");
    • @HamzaAhmedZia - 非常确定。我有这个在生产代码中运行。我使用的 SendGrid 版本是 4.0.30319(运行时),如属性中所示。还有一个版本字段,其中包含 6.1.0.0。
    • 虽然我在 webjob 控制台中取得了成功,但在遵循您的领导后我没有收到电子邮件。有什么想法吗?
    【解决方案2】:

    根据你的描述,我这边也做了一个测试demo,效果不错。我用的sendgird SDK是9.90。

    详细代码如下:

    class Program
    {
        static void Main(string[] args)
        {
    
             string  serializedEmail = args[0];
    
            Console.WriteLine($"SerializedEmail - {serializedEmail}");
    
            Customer customer = JsonConvert.DeserializeObject<Customer>(args[0]);
    
            //Customer customer = new Customer() { Name = "aaaa" };
            Execute(customer).Wait();
            Console.WriteLine(customer.Name);
            Console.ReadLine();
    
        }
    
    
        static async Task Execute(Customer customer)
        {
    
            var client = new SendGridClient("apikey");
            var from = new EmailAddress("sendgird@xxxxxx.com", "Example User");
            var subject = "Sending with SendGrid is Fun";
            var to = new EmailAddress("sendgird@xxxxxxx.com", "Example User");
            var plainTextContent = $"Name : {customer.Name}";
            var htmlContent = "<strong>and easy to do anywhere, even with C#</strong>";
            var msg = MailHelper.CreateSingleEmail(from, to, subject, plainTextContent, htmlContent);
            var response = await client.SendEmailAsync(msg);
        }
    
    
    }
    
    public class Customer
    {
        public string Name { get; set; }
    }
    

    但是我没有收到任何电子邮件

    我建议你可以先访问这个url,看看sendgird已经把邮件发到正确的邮箱了。

    结果是这样的:

    【讨论】:

    • 我 1. 尝试了您的代码 2. 创建了具有完全访问权限的新 sendgrid api 密钥但是我没有收到任何电子邮件。我怀疑您的控制台电子邮件正在通过,因为 console.readline() 在您的 main 函数末尾。我确认我没有通过 azure on demand web job 收到任何电子邮件。不过还是谢谢你的指导。还有其他想法吗?
    • 你检查过我说的查看发送邮件日志的url吗?
    • 是的,我做了app.sendgrid.com/email_activity?不幸的是,该屏幕上没有邮件:-(
    猜你喜欢
    • 2018-01-11
    • 2019-06-07
    • 1970-01-01
    • 1970-01-01
    • 2012-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-26
    相关资源
    最近更新 更多