使用 WebJobs 通过 SendGrid 发送电子邮件

Email sending with SendGrid using WebJobs

我正在尝试使用 WebJobs 将 SendGrid 集成到 .Net 4.5 应用程序中。

我完成了发送基本电子邮件所需的基本配置。我正在尝试 运行 并在我的本地机器上对其进行测试。我不知道如何将消息推送到队列。我现在无法升级应用程序的 .Net 版本。如果可以在不使用 webjobs 的情况下执行此操作,那也很好。

Program.cs

static void Main()
{

    var config = new JobHostConfiguration();
    config.UseTimers();
    config.Queues.MaxDequeueCount = 2;
    config.Queues.MaxPollingInterval = TimeSpan.FromSeconds(4);
    config.Queues.BatchSize = 2;

    if (config.IsDevelopment)
    {
        config.UseDevelopmentSettings();
    }

    config.UseSendGrid();

    var host = new JobHost(config);
    host.RunAndBlock();
}

Functions.cs

public static void ProcessQueueMessage([QueueTrigger("queue")] string message, TextWriter log, [SendGrid(From = "no-reply@company.com", To = "employee@company.com")] out Mail mail)
{
    log.WriteLine(message);

    mail = new Mail();

    var personalization = new Personalization();
    personalization.AddBcc(new Email("employee@company.com"));

    mail.AddPersonalization(personalization);
    mail.Subject = "Test Email Subject";
    mail.AddContent(new Content("text/html", $"The message '{message}' was successfully processed."));
}

找到以下函数: SendGrid_Test_002.Functions.ProcessQueueMessage ServicePointManager.DefaultConnectionLimit 设置为默认值 2。这可以限制对 Azure 存储等服务的连接吞吐量。有关详细信息,请参阅 https://aka.ms/webjobs-connections。 作业主机已启动

我在控制台上得到了这个。

提前致谢:)

我只需使用以下代码将消息送入 webjob 队列。

CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConnectionString"));

// Create the queue client.
CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient();

// Retrieve a reference to a container.
CloudQueue queue = queueClient.GetQueueReference("email-queue-name");

// Create the queue if it doesn't already exist
queue.CreateIfNotExists();

// Create message to be sent to the queue
CloudQueueMessage message = new CloudQueueMessage(JsonConvert.SerializeObject(new
{
    From = emailContent.From,
    To = emailContent.To,
    Cc = emailContent.Cc,
    Bcc = emailContent.Bcc,
    Subject = emailContent.Subject,
    Message = emailContent.Message
}).ToString());
queue.AddMessage(message);