如何用TypeScript版Azure SDK跟踪Azure通信服务邮件分析数据?含其他云方案
用TypeScript SDK追踪邮件分析数据方案
一、Azure Communication Service (ACS) 实现步骤
1. 环境准备与SDK安装
初始化TypeScript项目后,安装所需依赖:
npm install @azure/communication-email @azure/identity @azure/arm-monitor
@azure/communication-email:用于发送邮件并获取基础投递状态@azure/identity:通过DefaultAzureCredential完成ACS身份验证@azure/arm-monitor:用于查询Azure Monitor中的ACS邮件指标(发送量、失败数等)
2. 发送邮件并启用追踪
发送邮件时需开启追踪配置,以便收集打开数等数据:
import { EmailClient } from "@azure/communication-email"; const connectionString = "<你的ACS连接字符串>"; const emailClient = new EmailClient(connectionString); async function sendStudentInvite() { const message = { senderAddress: "donotreply@<你的ACS自定义域名>", recipients: { to: [{ address: "student@example.com" }] }, content: { subject: "学生邀请邮件", plainText: "请点击链接完成注册..." }, trackingSettings: { trackOpens: true, // 启用打开追踪 trackClicks: true // 可选:启用点击追踪 } }; const sendResult = await emailClient.send(message); console.log(`邮件发送ID: ${sendResult.id}`); // 可通过sendResult.id后续查询详细状态 } sendStudentInvite().catch(console.error);
3. 获取分析数据
(1)实时投递状态查询
通过邮件发送ID获取即时状态(送达/失败):
async function getDeliveryStatus(messageId: string) { const status = await emailClient.getSendStatus(messageId); console.log(`投递状态: ${status.status}`); console.log(`详细信息: ${status.error?.message || "无错误"}`); }
(2)每日聚合指标(发送量、失败数、送达数)
通过Azure Monitor SDK查询ACS的邮件指标,按日聚合:
import { MonitorManagementClient } from "@azure/arm-monitor"; import { DefaultAzureCredential } from "@azure/identity"; const credential = new DefaultAzureCredential(); const monitorClient = new MonitorManagementClient(credential, "<你的Azure订阅ID>"); async function getDailyEmailMetrics() { const metrics = await monitorClient.metrics.list( "/subscriptions/<订阅ID>/resourceGroups/<资源组>/providers/Microsoft.Communication/emailServices/<ACS邮件服务名称>", { metricnames: "EmailsSent,EmailsFailed,EmailsDelivered", timespan: "PT24H", // 过去24小时 aggregation: "Count", interval: "P1D" // 按日聚合 } ); for (const metric of metrics.value || []) { console.log(`${metric.name?.value}: ${metric.timeseries[0]?.data[0]?.count}`); } }
(3)打开数数据
ACS的邮件打开数据会存储在Azure Monitor日志中,可通过Kusto查询语句获取,或使用Azure Log Analytics SDK拉取:
AzureCommunicationEmailDeliveryLogs | where TimeGenerated > ago(24h) | where OperationName == "EmailOpen" | summarize count() by bin(TimeGenerated, 1d)
二、其他云提供商替代方案
1. AWS SES
- 使用
@aws-sdk/client-ses发送邮件,启用配置集(Configuration Set) 开启打开追踪 - 通过
@aws-sdk/client-cloudwatch查询发送量、失败数、送达数等指标,打开数可通过配置集关联的S3存储或CloudWatch Logs提取
2. Google Workspace Gmail API
- 用Gmail API发送邮件时添加自定义追踪参数,结合Google Analytics收集打开数据
- 发送/失败/送达状态可通过Gmail API的
users.messages.get接口查询,或通过Google Cloud Logging获取聚合数据
3. SendGrid
- 使用SendGrid Node.js SDK快速集成,平台自带内置分析面板,支持通过API拉取每日发送量、失败数、送达数、打开数等全量数据,无需额外配置追踪模块
内容的提问来源于stack exchange,提问作者VIMALRAJ S
相关产品推荐
相关产品推荐

