You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:基于Azure Queue Trigger与Azure Communication Service的消息转邮件示例

实现Azure Queue消息触发Azure Function发送ACS邮件

整体逻辑流程

Web API推送消息至Azure Queue → Queue Trigger类型的Azure Function自动触发 → 解析队列中的邮件参数 → 调用Azure Communication Service(ACS)发送邮件

1. 定义队列消息结构

先统一Web API发送到队列的消息格式,建议用JSON封装邮件所需核心参数:

{
  "toEmail": "recipient@example.com",
  "subject": "队列触发的测试邮件",
  "htmlContent": "<p>这是通过Azure Queue触发ACS发送的邮件内容</p>"
}

2. 编写Azure Function整合ACS邮件发送

以下以C#为例(Azure Function最常用的开发语言),实现队列触发+邮件发送的完整逻辑:

前置准备

在Function项目中安装NuGet包:Azure.Communication.Email

核心代码

using Azure.Communication.Email;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Extensions.Logging;
using System.Text.Json;

public class QueueToAcsEmailFunction
{
    private readonly EmailClient _acsEmailClient;
    private readonly ILogger<QueueToAcsEmailFunction> _logger;

    // 通过依赖注入初始化ACS客户端,从配置读取连接字符串
    public QueueToAcsEmailFunction(EmailClient emailClient, ILogger<QueueToAcsEmailFunction> logger)
    {
        _acsEmailClient = emailClient;
        _logger = logger;
    }

    [Function("QueueToAcsEmailFunction")]
    public async Task Run([QueueTrigger("your-queue-name", Connection = "AzureWebJobsStorage")] string queueMessage)
    {
        _logger.LogInformation("收到队列消息: {MessageContent}", queueMessage);

        try
        {
            // 解析队列消息为邮件请求模型
            var emailParams = JsonSerializer.Deserialize<EmailRequestParams>(queueMessage);
            if (emailParams == null)
            {
                _logger.LogError("队列消息格式无效,无法解析");
                return;
            }

            // 构建ACS邮件消息
            var acsEmailMessage = new EmailMessage(
                senderAddress: "verified-sender@your-acs-domain.com", // ACS已验证的发件人邮箱
                recipientAddress: emailParams.ToEmail,
                subject: emailParams.Subject,
                htmlContent: emailParams.HtmlContent);

            // 发送邮件并等待结果
            var sendResult = await _acsEmailClient.SendAsync(WaitUntil.Completed, acsEmailMessage);
            _logger.LogInformation("邮件发送成功,消息ID: {MessageId},状态: {Status}", sendResult.MessageId, sendResult.Status);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "处理队列消息并发送邮件失败");
            // 可选逻辑:将失败消息移入死信队列,或配置Function重试策略
        }
    }

    // 邮件请求参数模型
    public class EmailRequestParams
    {
        public string ToEmail { get; set; }
        public string Subject { get; set; }
        public string HtmlContent { get; set; }
    }
}

配置项设置

在local.settings.json(本地开发)或Azure Function应用设置(生产环境)中添加:

  • AzureWebJobsStorage: Azure存储账户连接字符串(用于连接Queue)
  • CommunicationServicesConnectionString: ACS的连接字符串(从Azure门户ACS实例获取)

3. 关键注意事项

  • 确保ACS已配置并验证发件人邮箱:需在Azure门户ACS的「邮件服务」中添加发件人域名/邮箱并完成验证,否则无法发送邮件
  • 异常处理:针对消息解析失败、邮件发送超时/失败等场景,建议配置Azure Function的重试策略,或手动将无效消息移入死信队列
  • 消息一致性:Web API发送的队列消息结构必须与Function中解析的模型完全匹配,避免序列化错误
  • 配置管理:通过依赖注入读取配置,不要硬编码连接字符串,便于后续环境切换和维护

内容的提问来源于stack exchange,提问作者ani H

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 06:33:15