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ínhGiá Trị
Nền TảngMailgun (by Sinch)
Danh MụcEmail Marketing
Độ Phức Tạp Thiết LậpDễ
Tích Hợp Chính ThứcKhông
Dữ Liệu Đồng BộSự Kiện, Contacts, Deliverability, Campaigns
Phương Thức AuthAPI 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ó:

  1. Tài khoản Mailgun với verified sending domain
  2. Mailgun API key từ Mailgun Dashboard
  3. Tài khoản Brevo với quyền truy cập API
  4. 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:

Terminal window
# Lấy API key từ https://app.mailgun.com/settings/api_security
export MAILGUN_API_KEY=key-your-api-key
export MAILGUN_DOMAIN=your-domain.com
export TAJO_API_KEY=your_tajo_api_key
export BREVO_API_KEY=your_brevo_api_key
// Định dạng HTTP Basic Auth
const 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_UNSUBSCRIBED

API Endpoints

EndpointPhương ThứcMô Tả
https://api.mailgun.net/v3/{domain}/messagesPOSTGửi email messages
https://api.mailgun.net/v3/{domain}/eventsGETTruy vấn event logs
https://api.mailgun.net/v3/{domain}/bouncesGETLiệt kê bounces
https://api.mailgun.net/v3/{domain}/complaintsGETLiệt kê complaints
https://api.mailgun.net/v3/{domain}/unsubscribesGETLiệt kê unsubscribes
https://api.mailgun.net/v3/{domain}/tagsGETLiệt kê tags
https://api.mailgun.net/v3/{domain}/tags/{tag}/statsGETLấy tag statistics
https://api.mailgun.net/v3/listsGETLiệt kê mailing lists
https://api.mailgun.net/v3/domainsGETLiệt kê domains
https://api.mailgun.net/v4/address/validatePOSTXá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 Mailgun
const formData = new URLSearchParams();
formData.append('from', `Your App <noreply@${domain}>`);
formData.append('to', '[email protected]');
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 data
const 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ơn
if (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 Độ

EndpointGiới HạnGhi Chú
Messages APITheo gói100/giờ (free), không giới hạn (trả phí)
Events APIKhông có giới hạn rõ ràngSử dụng phân trang với tối đa 300 items
Validation APIDựa trên góiPay-per-validation
WebhooksThời gian thựcKhông giới hạn tốc độ giao hàng
Suppressions APIKhông có giới hạn rõ ràngRate 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ânGiải Pháp
401 UnauthorizedAPI key không hợp lệXác minh API key trong Mailgun dashboard
Domain chưa xác minhDNS records thiếuThêm TXT, CNAME, MX records cần thiết
Webhook không nhậnURL không thể truy cậpĐảm bảo webhook URL có thể truy cập công khai
Events thiếuKhoảng thời gian quá hẹpMở rộng tham số begin/end
Deliverability thấpDomain reputationKiểm tra domain stats và authentication

Thực Hành Tốt Nhất

  1. Xác minh sending domains - Hoàn thành DNS verification để deliverability tối ưu
  2. Sử dụng webhooks cho events - Giao hàng webhook thời gian thực vs. polling Events API
  3. Xử lý bounces chủ động - Suppress hard bounces ngay lập tức trong Brevo
  4. Gắn tags cho messages - Sử dụng tags để phân loại và phân tích hiệu suất email
  5. Theo dõi domain reputation - Giám sát deliverability metrics trong Mailgun dashboard
  6. 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

Tài Nguyên Liên Quan

Subscribe to updates

developer-docs

Drop your email or phone number — we'll send you what matters next.

auto-detect
Trợ lý AI

Xin chào! Hãy hỏi tôi về tài liệu.