
? SendGrid 多语言开发集成指南:实时数据追踪设置教程
? 多语言开发集成基础
选择合适的开发语言
安装 SendGrid 客户端库
pip install sendgrid==6.9.6
发送多语言邮件
Content
对象来包含不同语言的文本:from sendgrid.helpers.mail import Mail
message = Mail(
from_email='from@example.com',
to_emails='to@example.com',
subject='多语言邮件测试',
html_content='这是一封中文邮件。
This is an English email.
'
)
const sgMail = require('@sendgrid/mail');
sgMail.setApiKey(process.env.SENDGRID_API_KEY);
const msg = {
to: 'to@example.com',
from: 'from@example.com',
subject: '多语言模板邮件',
templateId: 'd-1234567890',
dynamicTemplateData: {
content: '这是模板中的动态内容。'
}
};
sgMail.send(msg);
? 实时数据追踪设置
启用事件 Webhook
处理 Webhook 事件
from flask import Flask, request
app = Flask(__name__)
@app.route('/event', methods=['POST'])
def event_webhook():
event = request.json[]
if event['event'] == 'delivered':
print('邮件已送达')
elif event['event'] == 'open':
print('邮件已打开')
elif event['event'] == 'click':
print('链接已点击')
return {'status': 'ok'}
if __name__ == '__main__':
app.run(debug=True)
const express = require('express');
const app = express();
app.use(express.json());
app.post('/event', (req, res) => {
const event = req.body[];
switch (event.event) {
case 'delivered':
console.log('邮件已送达');
break;
case 'open':
console.log('邮件已打开');
break;
case 'click':
console.log('链接已点击');
break;
}
res.status().send('ok');
});
app.listen(, () => {
console.log('Webhook 服务启动');
});
验证 Webhook 签名
const crypto = require('crypto');
app.post('/event', (req, res) => {
const signature = req.headers['x-twilio-email-event-webhook-signature'];
const timestamp = req.headers['x-twilio-email-event-webhook-timestamp'];
const body = JSON.stringify(req.body);
const hmac = crypto.createHmac('sha256', process.env.SENDGRID_WEBHOOK_SECRET);
const digest = hmac.update(timestamp + body).digest('hex');
if (digest === signature) {
// 处理事件
res.status().send('ok');
} else {
res.status().send('签名验证失败');
}
});
?️ 高级功能与最佳实践
异步发送邮件
import asyncio
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail
async def send_email_async():
message = Mail(
from_email='from@example.com',
to_emails='to@example.com',
subject='异步邮件测试',
html_content='这是一封异步发送的邮件。
'
)
try:
sg = SendGridAPIClient(api_key=os.environ.get('SENDGRID_API_KEY'))
response = await sg.send(message)
print(response.status_code)
except Exception as e:
print(e)
asyncio.run(send_email_async())
批量发送邮件
require 'vendor/autoload.php';
use SendGrid\Mail\Mail;
use SendGrid\SendGrid;
$apiKey = getenv('SENDGRID_API_KEY');
$sg = new SendGrid($apiKey);
$message = new Mail();
$message->setFrom('from@example.com', '发件人');
$message->setSubject('批量邮件测试');
$personalization = new \SendGrid\Mail\Personalization();
$personalization->addTo('to1@example.com', '收件人1');
$personalization->addTo('to2@example.com', '收件人2');
$personalization->addDynamicTemplateData('content', '这是批量邮件的内容。');
$message->addPersonalization($personalization);
$message->setTemplateId('d-1234567890');
try {
$response = $sg->send($message);
print $response->statusCode() . "\n";
} catch (Exception $e) {
echo 'Caught exception: ' . $e->getMessage() . "\n";
}
数据分析与可视化
? 常见问题与解决方案
邮件内容乱码
message = Mail(
from_email='from@example.com',
to_emails='to@example.com',
subject='测试邮件',
html_content='这是一封 UTF-8 编码的邮件。
'
)
这是一封 UTF-8 编码的邮件。
'