Trình Kết Nối Mailgun
Kết nối Mailgun với Brevo qua Tajo để hợp nhất dữ liệu email giao dịch và marketing, đồng bộ delivery events và engagement metrics, và hợp nhất hạ tầng email của bạn vào customer view đơn nhất.
Tổng Quan
| Thuộc Tính | Giá Trị |
|---|---|
| Nền Tảng | Mailgun (by Sinch) |
| Danh Mục | Email Marketing |
| Độ Phức Tạp Thiết Lập | Dễ |
| Tích Hợp Chính Thức | Không |
| Dữ Liệu Đồng Bộ | Sự Kiện, Contacts, Deliverability, Campaigns |
| Phương Thức Auth | API Key (HTTP Basic Auth) |
Tính Năng
- Đồng bộ delivery events - Theo dõi delivered, bounced, opened và clicked events
- Số liệu tương tác - Đồng bộ open và click rates sang thuộc tính liên hệ Brevo
- Quản lý bounce - Tự động suppress địa chỉ đã bounce trong Brevo
- Xử lý complaint - Đồng bộ spam complaints để vệ sinh danh sách
- Reputation domain - Theo dõi sức khỏe và deliverability của sending domain
- Theo dõi email giao dịch - Tương quan transactional sends với marketing data
Yêu Cầu
Trước khi bắt đầu, hãy đảm bảo bạn có:
- Tài khoản Mailgun với verified sending domain
- Mailgun API key từ Mailgun Dashboard
- Tài khoản Brevo với quyền truy cập API
- Tài khoản Tajo với connector permissions
Xác Thực
Xác Thực API Key
Mailgun sử dụng HTTP Basic Authentication với api là username và API key là password:
# Lấy API key từ https://app.mailgun.com/settings/api_securityexport MAILGUN_API_KEY=key-your-api-keyexport MAILGUN_DOMAIN=your-domain.comexport TAJO_API_KEY=your_tajo_api_keyexport BREVO_API_KEY=your_brevo_api_key// Định dạng HTTP Basic Authconst headers = { 'Authorization': `Basic ${Buffer.from( `api:${process.env.MAILGUN_API_KEY}` ).toString('base64')}`};
// Hoặc dùng curl// curl -s --user 'api:YOUR_API_KEY' ...Loại API Key
Mailgun cung cấp domain-specific sending keys và account-level API keys. Sử dụng domain sending keys cho các thao tác gửi tin và account API key cho management operations.
Cấu Hình
Thiết Lập Cơ Bản
connectors: mailgun: enabled: true api_key: "${MAILGUN_API_KEY}" domain: "${MAILGUN_DOMAIN}" region: "us" # hoặc "eu" cho vùng EU
sync: events: true contacts: true bounces: true complaints: true schedule: "*/15 * * * *" # Mỗi 15 phút
webhook: signing_key: "${MAILGUN_WEBHOOK_SIGNING_KEY}"
lists: engaged: 30 bounced: 31 complained: 32Ánh Xạ Trường
field_mapping: email: email first_name: FIRSTNAME last_name: LASTNAME open_rate: MG_OPEN_RATE click_rate: MG_CLICK_RATE last_delivered: MG_LAST_DELIVERED bounce_type: MG_BOUNCE_TYPE engagement_score: MG_ENGAGEMENT unsubscribed: MG_UNSUBSCRIBEDAPI Endpoints
| Endpoint | Phương Thức | Mô Tả |
|---|---|---|
https://api.mailgun.net/v3/{domain}/messages | POST | Gửi email messages |
https://api.mailgun.net/v3/{domain}/events | GET | Truy vấn event logs |
https://api.mailgun.net/v3/{domain}/bounces | GET | Liệt kê bounces |
https://api.mailgun.net/v3/{domain}/complaints | GET | Liệt kê complaints |
https://api.mailgun.net/v3/{domain}/unsubscribes | GET | Liệt kê unsubscribes |
https://api.mailgun.net/v3/{domain}/tags | GET | Liệt kê tags |
https://api.mailgun.net/v3/{domain}/tags/{tag}/stats | GET | Lấy tag statistics |
https://api.mailgun.net/v3/lists | GET | Liệt kê mailing lists |
https://api.mailgun.net/v3/domains | GET | Liệt kê domains |
https://api.mailgun.net/v4/address/validate | POST | Xác thực địa chỉ email |
Vùng EU
Cho tài khoản Mailgun EU, sử dụng https://api.eu.mailgun.net thay vì https://api.mailgun.net cho tất cả API endpoints.
Ví Dụ Code
Khởi Tạo Trình Kết Nối
import { TajoClient } from '@tajo/sdk';
const tajo = new TajoClient({ apiKey: process.env.TAJO_API_KEY, brevoApiKey: process.env.BREVO_API_KEY});
await tajo.connectors.connect('mailgun', { apiKey: process.env.MAILGUN_API_KEY, domain: process.env.MAILGUN_DOMAIN, region: 'us'});Gửi Tin Qua Mailgun API
// Gửi email sử dụng Messages API của Mailgunconst formData = new URLSearchParams();formData.append('from', `Your App <noreply@${domain}>`);formData.append('subject', 'Chào mừng bạn đến với nền tảng của chúng tôi');formData.append('html', '<h1>Chào mừng!</h1><p>Cảm ơn bạn đã đăng ký.</p>');formData.append('o:tag', 'welcome-email');formData.append('o:tracking', 'yes');
const response = await fetch( `https://api.mailgun.net/v3/${domain}/messages`, { method: 'POST', headers: { 'Authorization': `Basic ${Buffer.from(`api:${apiKey}`).toString('base64')}` }, body: formData });
const result = await response.json();// { id: '<[email protected]>', message: 'Queued. Thank you.' }Đồng Bộ Email Events Sang Brevo
// Truy vấn Mailgun events và đồng bộ engagement dataconst eventsResponse = await fetch( `https://api.mailgun.net/v3/${domain}/events?` + new URLSearchParams({ begin: lastSyncDate, ascending: 'yes', limit: 300, event: 'delivered OR opened OR clicked' }), { headers: { 'Authorization': `Basic ${Buffer.from(`api:${apiKey}`).toString('base64')}` } });
const { items, paging } = await eventsResponse.json();
for (const event of items) { const email = event.recipient;
switch (event.event) { case 'delivered': await tajo.contacts.update(email, { attributes: { MG_LAST_DELIVERED: event.timestamp } }); break; case 'opened': await tajo.events.track({ email, event: 'email_opened', properties: { subject: event.message.headers.subject } }); break; case 'clicked': await tajo.events.track({ email, event: 'email_clicked', properties: { url: event.url } }); break; }}
// Theo dõi phân trang cho nhiều events hơnif (paging.next) { // Lấy trang tiếp theo sử dụng URL paging.next}Xử Lý Mailgun Webhooks
const crypto = require('crypto');
app.post('/webhooks/mailgun', async (req, res) => { // Xác minh webhook signature const { timestamp, token, signature } = req.body.signature; const encodedToken = crypto .createHmac('sha256', process.env.MAILGUN_WEBHOOK_SIGNING_KEY) .update(timestamp.concat(token)) .digest('hex');
if (encodedToken !== signature) { return res.status(401).send('Unauthorized'); }
const eventData = req.body['event-data']; const event = eventData.event; const email = eventData.recipient;
await tajo.connectors.handleWebhook('mailgun', { topic: event, payload: eventData });
// Xử lý bounce suppression if (event === 'failed' && eventData.severity === 'permanent') { await tajo.contacts.update(email, { attributes: { MG_BOUNCE_TYPE: 'hard_bounce' }, emailBlacklisted: true }); }
res.status(200).send('OK');});Giới Hạn Tốc Độ
| Endpoint | Giới Hạn | Ghi Chú |
|---|---|---|
| Messages API | Theo gói | 100/giờ (free), không giới hạn (trả phí) |
| Events API | Không có giới hạn rõ ràng | Sử dụng phân trang với tối đa 300 items |
| Validation API | Dựa trên gói | Pay-per-validation |
| Webhooks | Thời gian thực | Không giới hạn tốc độ giao hàng |
| Suppressions API | Không có giới hạn rõ ràng | Rate limiting tiêu chuẩn áp dụng |
Giới Hạn Gửi
Mailgun áp dụng giới hạn gửi dựa trên gói và domain reputation của bạn. Domains mới bắt đầu với giới hạn thấp hơn và tăng dần khi sender reputation cải thiện. Theo dõi domain stats trong Mailgun dashboard.
Khắc Phục Sự Cố
| Sự Cố | Nguyên Nhân | Giải Pháp |
|---|---|---|
| 401 Unauthorized | API key không hợp lệ | Xác minh API key trong Mailgun dashboard |
| Domain chưa xác minh | DNS records thiếu | Thêm TXT, CNAME, MX records cần thiết |
| Webhook không nhận | URL không thể truy cập | Đảm bảo webhook URL có thể truy cập công khai |
| Events thiếu | Khoảng thời gian quá hẹp | Mở rộng tham số begin/end |
| Deliverability thấp | Domain reputation | Kiểm tra domain stats và authentication |
Thực Hành Tốt Nhất
- Xác minh sending domains - Hoàn thành DNS verification để deliverability tối ưu
- Sử dụng webhooks cho events - Giao hàng webhook thời gian thực vs. polling Events API
- Xử lý bounces chủ động - Suppress hard bounces ngay lập tức trong Brevo
- Gắn tags cho messages - Sử dụng tags để phân loại và phân tích hiệu suất email
- Theo dõi domain reputation - Giám sát deliverability metrics trong Mailgun dashboard
- Sử dụng email validation - Xác thực địa chỉ trước khi thêm vào danh sách Brevo
Bảo Mật
- HTTP Basic Auth - API key truyền qua Authorization header
- Webhook signatures - Xác minh chữ ký HMAC-SHA256
- Domain verification - Xác thực DNS SPF, DKIM và DMARC
- IP whitelisting - Có sẵn cho dedicated IP plans
- Mã hóa TLS - Tất cả API endpoints yêu cầu HTTPS
- Key rotation - Thay đổi API keys định kỳ qua Mailgun dashboard