Back to Blog返回博客Volver al BlogRetour au Blogブログに戻るZurück zum BlogVoltar ao Blog블로그로 돌아가기Назад в блогالعودة إلى المدونة
Node.js Python Email API GridInbox REST API SES Node.js Python 邮件 API GridInbox REST API SES

Send Email API Node.js Python: Complete Tutorial with Code Examples Node.js 和 Python 发送邮件 API 完整教程:附代码示例

· 8 min read阅读时间:8 分钟

Every developer eventually needs to send email from their application. Whether it's transactional emails, notifications, or team replies, a reliable email API is essential. In this tutorial, you will learn to send email via API in Node.js and Python using the GridInbox REST API. We cover authentication, sending messages with attachments, handling webhooks, and real-world patterns you can copy and paste today.

GridInbox provides a REST API for sending and receiving email from unlimited aliases with custom domains.

GridInbox is a multi-tenant email alias management SaaS that works with AWS SES and Cloudflare Email Routing. Its REST API lets you programmatically send and receive email from any alias you own. You can manage shared team inboxes with role-based access control (RBAC), attach files, and handle incoming email via webhooks. All examples below use real API endpoints and real responses.

Prerequisites

  • A GridInbox account with at least one verified domain
  • An API key (found in your GridInbox dashboard under Settings > API Keys)
  • Node.js 18+ or Python 3.8+ installed locally
  • curl for quick testing (optional)

Authentication with the GridInbox API uses a simple bearer token in the Authorization header.

Every request to the GridInbox API must include an Authorization: Bearer YOUR_API_KEY header. Your API key is a 64-character string that identifies your account. Keep it secret; never expose it in client-side code.

Here is a quick test using curl to verify your key works:

curl -X GET https://api.gridinbox.com/v1/me \
  -H "Authorization: Bearer gi_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"

If your key is valid, you receive a JSON response with your account details and a 200 status code. A 401 means the key is invalid or missing.

Bearer Token: A credential string sent in the HTTP Authorization header to authenticate API requests. GridInbox uses bearer tokens exclusively.

How to send a simple email via API in Node.js and Python.

The POST /v1/send endpoint accepts a JSON body with from, to, subject, and body fields. Below are complete, runnable examples in both languages.

Node.js (using fetch, no external dependencies)

const API_KEY = 'gi_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';

async function sendEmail() {
  const response = await fetch('https://api.gridinbox.com/v1/send', {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${API_KEY}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      from: 'hello@yourdomain.com',
      to: ['user@example.com'],
      subject: 'Hello from GridInbox',
      body: 'This email was sent via the GridInbox API using Node.js.'
    })
  });
  const data = await response.json();
  console.log(data);
}

sendEmail();

Python (using requests)

import requests

API_KEY = 'gi_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'

response = requests.post(
    'https://api.gridinbox.com/v1/send',
    headers={
        'Authorization': f'Bearer {API_KEY}',
        'Content-Type': 'application/json'
    },
    json={
        'from': 'hello@yourdomain.com',
        'to': ['user@example.com'],
        'subject': 'Hello from GridInbox',
        'body': 'This email was sent via the GridInbox API using Python.'
    }
)
print(response.json())

Both examples send a plain text email. The response includes an id field (e.g., "msg_abc123") that you can use to track delivery status later.

Attachments are supported via base64-encoded content in the API request.

To attach a file, add an attachments array to your request body. Each attachment requires a filename, content (base64-encoded string), and contentType (MIME type). Maximum attachment size per email is 25 MB total.

Node.js example with attachment

const fs = require('fs');

async function sendWithAttachment() {
  const fileBuffer = fs.readFileSync('./invoice.pdf');
  const base64Content = fileBuffer.toString('base64');

  const response = await fetch('https://api.gridinbox.com/v1/send', {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${API_KEY}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      from: 'billing@yourdomain.com',
      to: ['client@example.com'],
      subject: 'Your invoice',
      body: 'Please find your invoice attached.',
      attachments: [
        {
          filename: 'invoice.pdf',
          content: base64Content,
          contentType: 'application/pdf'
        }
      ]
    })
  });
  console.log(await response.json());
}

Python example with attachment

import base64

with open('invoice.pdf', 'rb') as f:
    encoded = base64.b64encode(f.read()).decode('utf-8')

response = requests.post(
    'https://api.gridinbox.com/v1/send',
    headers={
        'Authorization': f'Bearer {API_KEY}',
        'Content-Type': 'application/json'
    },
    json={
        'from': 'billing@yourdomain.com',
        'to': ['client@example.com'],
        'subject': 'Your invoice',
        'body': 'Please find your invoice attached.',
        'attachments': [
            {
                'filename': 'invoice.pdf',
                'content': encoded,
                'contentType': 'application/pdf'
            }
        ]
    }
)
print(response.json())

GridInbox automatically attaches the file to the outgoing email. You can attach up to 10 files per email.

Webhooks notify your application when an email is delivered, bounced, or replied to.

GridInbox can send HTTP POST requests to a URL you specify whenever events occur. Common events include delivered, bounced, opened, and replied. Webhooks give you real-time feedback without polling.

Setting up a webhook endpoint in Node.js (Express)

const express = require('express');
const app = express();

app.use(express.json());

app.post('/webhooks/gridinbox', (req, res) => {
  const event = req.body;
  console.log('Received event:', event.type);
  
  if (event.type === 'delivered') {
    // Update your database: email delivered
    console.log(`Email ${event.message_id} delivered`);
  } else if (event.type === 'bounced') {
    // Handle bounce: remove from list
    console.log(`Email ${event.message_id} bounced: ${event.reason}`);
  }
  
  res.status(200).send('OK');
});

app.listen(3000, () => console.log('Webhook listener on port 3000'));

Setting up a webhook endpoint in Python (Flask)

from flask import Flask, request, jsonify

app = Flask(__name__)

@app.route('/webhooks/gridinbox', methods=['POST'])
def handle_webhook():
    event = request.json
    print(f"Received event: {event['type']}")
    
    if event['type'] == 'delivered':
        print(f"Email {event['message_id']} delivered")
    elif event['type'] == 'bounced':
        print(f"Email {event['message_id']} bounced: {event['reason']}")
    
    return 'OK', 200

if __name__ == '__main__':
    app.run(port=3000)

After deploying your endpoint, configure the webhook URL in the GridInbox dashboard under Webhooks. Choose which events to forward. GridInbox will retry failed deliveries up to 3 times with exponential backoff.

Error handling and rate limits keep your integration robust.

The GridInbox API returns standard HTTP status codes. A 429 status means you hit the rate limit (100 requests per second for paid plans). A 400 status indicates a validation error, such as a missing to field or an invalid email address. Always check response.ok or response.status in your code.

// Node.js: checking for errors
if (!response.ok) {
  const error = await response.json();
  console.error(`Error ${response.status}: ${error.message}`);
}
# Python: checking for errors
if response.status_code != 200:
    error = response.json()
    print(f"Error {response.status_code}: {error['message']}")

Retry with exponential backoff when you receive a 429. Wait at least 1 second before retrying, then double the wait each time. Most SDKs handle this automatically, but raw API users should implement it.

Real-world example: sending a transactional email with a template.

Suppose you run a SaaS and need to send a welcome email with the user's name and a link. Store your email templates on your server and substitute variables before sending.

// Node.js: welcome email with template
const template = `Hi {{name}},\n\nWelcome to our platform! Get started here: {{link}}\n\nBest,\nThe Team`;

async function sendWelcomeEmail(userName, userEmail, link) {
  const body = template
    .replace('{{name}}', userName)
    .replace('{{link}}', link);

  const response = await fetch('https://api.gridinbox.com/v1/send', {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${API_KEY}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      from: 'welcome@yourdomain.com',
      to: [userEmail],
      subject: 'Welcome to our platform!',
      body: body
    })
  });
  return response.json();
}

In production, you might send 10,000 welcome emails per day. GridInbox handles that volume without issues when using AWS SES as the underlying provider. The API response includes a message_id you can store for future reference.

Best practices for sending email via API in Node.js and Python.

  • Always validate email addresses server-side before sending. GridInbox does basic validation, but pre-checking reduces bounces.
  • Use environment variables for your API key. Never hardcode it.
  • Implement idempotency keys if you might retry the same request. GridInbox supports an optional idempotency_key header.
  • Monitor your bounce rate. A rate above 5% can hurt your sender reputation. GridInbox's webhooks help you react fast.
  • Test with a small batch first. Send 10 emails, check delivery, then ramp up.

Frequently Asked Questions

How do I send an email using Node.js and Python?

Use the GridInbox REST API endpoint POST /v1/send with a bearer token. In Node.js use fetch; in Python use the requests library. Pass the from, to, subject, and body fields in JSON.

What is the best email API for Node.js and Python developers?

GridInbox is a strong choice because it offers a simple REST API, supports unlimited aliases and custom domains, works with AWS SES, and provides webhooks for delivery tracking.

Can I send attachments with the email API?

Yes. Include an attachments array in your request body with base64-encoded content, filename, and MIME type. Maximum total attachment size is 25 MB with up to 10 files.

How do I handle email delivery status in my app?

Set up a webhook endpoint on your server and configure GridInbox to send events like delivered, bounced, or opened to that URL. GridInbox retries failed webhooks up to 3 times.

What are the rate limits for the GridInbox API?

Paid plans support 100 requests per second. Starter plans have a limit of 10 requests per second. If you exceed the limit, you receive a 429 status code.

Do I need to use AWS SES or Cloudflare with GridInbox?

GridInbox works with AWS SES and Cloudflare Email Routing as underlying providers, but you do not need to manage them directly. GridInbox handles the configuration for you.

每个开发者最终都需要从自己的应用中发送邮件。无论是事务性邮件、通知还是团队回复,一个可靠的邮件 API 都是必不可少的。在本教程中,你将学习如何使用 GridInbox REST API 在 Node.js 和 Python 中通过 API 发送邮件。我们将涵盖身份验证、发送带附件的消息、处理 Webhook,以及你可以直接复制粘贴的实战模式。

GridInbox 提供 REST API,支持从自定义域名的无限别名发送和接收邮件。

GridInbox 是一个多租户邮件别名管理 SaaS,可与 AWS SES 和 Cloudflare Email Routing 配合使用。其 REST API 让你能够以编程方式从你拥有的任何别名发送和接收邮件。你可以管理具有基于角色的访问控制(RBAC)的共享团队收件箱、附加文件,并通过 Webhook 处理传入邮件。以下所有示例均使用真实的 API 端点和真实响应。

前提条件

  • 一个 GridInbox 账户,且至少拥有一个已验证域名
  • 一个 API 密钥(在 GridInbox 控制台的“设置”>“API 密钥”中获取)
  • 本地安装 Node.js 18+ 或 Python 3.8+
  • curl 用于快速测试(可选)

GridInbox API 的身份验证使用 Authorization 头中的简单 Bearer Token。

对 GridInbox API 的每个请求都必须包含 Authorization: Bearer YOUR_API_KEY 头。你的 API 密钥是一个 64 字符的字符串,用于标识你的账户。请妥善保管,切勿在客户端代码中暴露。

以下是一个使用 curl 快速验证密钥是否有效的测试:

curl -X GET https://api.gridinbox.com/v1/me \
  -H "Authorization: Bearer gi_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"

如果密钥有效,你将收到一个包含账户详细信息的 JSON 响应,状态码为 200。状态码 401 表示密钥无效或缺失。

Bearer Token:一种在 HTTP Authorization 头中发送的凭证字符串,用于验证 API 请求。GridInbox 仅使用 Bearer Token。

如何在 Node.js 和 Python 中通过 API 发送一封简单的邮件。

POST /v1/send 端点接受一个包含 from、to、subject 和 body 字段的 JSON 请求体。以下是两种语言的完整可运行示例。

Node.js(使用 fetch,无需外部依赖)

const API_KEY = 'gi_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';

async function sendEmail() {
  const response = await fetch('https://api.gridinbox.com/v1/send', {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${API_KEY}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      from: 'hello@yourdomain.com',
      to: ['user@example.com'],
      subject: 'Hello from GridInbox',
      body: 'This email was sent via the GridInbox API using Node.js.'
    })
  });
  const data = await response.json();
  console.log(data);
}

sendEmail();

Python(使用 requests)

import requests

API_KEY = 'gi_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'

response = requests.post(
    'https://api.gridinbox.com/v1/send',
    headers={
        'Authorization': f'Bearer {API_KEY}',
        'Content-Type': 'application/json'
    },
    json={
        'from': 'hello@yourdomain.com',
        'to': ['user@example.com'],
        'subject': 'Hello from GridInbox',
        'body': 'This email was sent via the GridInbox API using Python.'
    }
)
print(response.json())

两个示例都发送了一封纯文本邮件。响应中包含一个 id 字段(例如 "msg_abc123"),你可以用它来跟踪后续的投递状态。

通过 API 请求中的 base64 编码内容支持附件。

要附加文件,请在请求体中添加一个 attachments 数组。每个附件需要包含 filename(文件名)、content(base64 编码的字符串)和 contentType(MIME 类型)。每封邮件的最大附件总大小为 25 MB。

Node.js 带附件的示例

const fs = require('fs');

async function sendWithAttachment() {
  const fileBuffer = fs.readFileSync('./invoice.pdf');
  const base64Content = fileBuffer.toString('base64');

  const response = await fetch('https://api.gridinbox.com/v1/send', {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${API_KEY}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      from: 'billing@yourdomain.com',
      to: ['client@example.com'],
      subject: 'Your invoice',
      body: 'Please find your invoice attached.',
      attachments: [
        {
          filename: 'invoice.pdf',
          content: base64Content,
          contentType: 'application/pdf'
        }
      ]
    })
  });
  console.log(await response.json());
}

Python 带附件的示例

import base64

with open('invoice.pdf', 'rb') as f:
    encoded = base64.b64encode(f.read()).decode('utf-8')

response = requests.post(
    'https://api.gridinbox.com/v1/send',
    headers={
        'Authorization': f'Bearer {API_KEY}',
        'Content-Type': 'application/json'
    },
    json={
        'from': 'billing@yourdomain.com',
        'to': ['client@example.com'],
        'subject': 'Your invoice',
        'body': 'Please find your invoice attached.',
        'attachments': [
            {
                'filename': 'invoice.pdf',
                'content': encoded,
                'contentType': 'application/pdf'
            }
        ]
    }
)
print(response.json())

GridInbox 会自动将文件附加到外发邮件中。每封邮件最多可附加 10 个文件。

Webhook 会在邮件被投递、退回或回复时通知你的应用。

当事件发生时,GridInbox 可以向你指定的 URL 发送 HTTP POST 请求。常见事件包括 delivered(已投递)、bounced(已退回)、opened(已打开)和 replied(已回复)。Webhook 让你无需轮询即可获得实时反馈。

在 Node.js(Express)中设置 Webhook 端点

const express = require('express');
const app = express();

app.use(express.json());

app.post('/webhooks/gridinbox', (req, res) => {
  const event = req.body;
  console.log('Received event:', event.type);
  
  if (event.type === 'delivered') {
    // 更新数据库:邮件已投递
    console.log(`Email ${event.message_id} delivered`);
  } else if (event.type === 'bounced') {
    // 处理退回:从列表中移除
    console.log(`Email ${event.message_id} bounced: ${event.reason}`);
  }
  
  res.status(200).send('OK');
});

app.listen(3000, () => console.log('Webhook listener on port 3000'));

在 Python(Flask)中设置 Webhook 端点

from flask import Flask, request, jsonify

app = Flask(__name__)

@app.route('/webhooks/gridinbox', methods=['POST'])
def handle_webhook():
    event = request.json
    print(f"Received event: {event['type']}")
    
    if event['type'] == 'delivered':
        print(f"Email {event['message_id']} delivered")
    elif event['type'] == 'bounced':
        print(f"Email {event['message_id']} bounced: {event['reason']}")
    
    return 'OK', 200

if __name__ == '__main__':
    app.run(port=3000)

部署你的端点后,在 GridInbox 控制台的“Webhook”下配置 Webhook URL。选择要转发的事件。GridInbox 会以指数退避方式重试失败的投递,最多 3 次。

错误处理和速率限制让你的集成更健壮。

GridInbox API 返回标准的 HTTP 状态码。状态码 429 表示你达到了速率限制(付费计划为每秒 100 个请求)。状态码 400 表示验证错误,例如缺少 to 字段或电子邮件地址无效。务必在代码中检查 response.ok 或 response.status。

// Node.js:检查错误
if (!response.ok) {
  const error = await response.json();
  console.error(`Error ${response.status}: ${error.message}`);
}
# Python:检查错误
if response.status_code != 200:
    error = response.json()
    print(f"Error {response.status_code}: {error['message']}")

当收到 429 状态码时,使用指数退避重试。至少等待 1 秒再重试,然后每次将等待时间加倍。大多数 SDK 会自动处理此问题,但原始 API 用户应自行实现。

实战示例:使用模板发送事务性邮件。

假设你运营一个 SaaS,需要发送一封包含用户名和链接的欢迎邮件。将邮件模板存储在你的服务器上,并在发送前替换变量。

// Node.js:带模板的欢迎邮件
const template = `Hi {{name}},\n\nWelcome to our platform! Get started here: {{link}}\n\nBest,\nThe Team`;

async function sendWelcomeEmail(userName, userEmail, link) {
  const body = template
    .replace('{{name}}', userName)
    .replace('{{link}}', link);

  const response = await fetch('https://api.gridinbox.com/v1/send', {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${API_KEY}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      from: 'welcome@yourdomain.com',
      to: [userEmail],
      subject: 'Welcome to our platform!',
      body: body
    })
  });
  return response.json();
}

在生产环境中,你可能每天发送 10,000 封欢迎邮件。当使用 AWS SES 作为底层提供商时,GridInbox 可以轻松处理该量级。API 响应中包含一个 message_id,你可以存储起来供将来参考。

在 Node.js 和 Python 中通过 API 发送邮件的最佳实践。

  • 始终在服务器端验证电子邮件地址后再发送。GridInbox 会进行基本验证,但预先检查可以减少退回。
  • 使用环境变量存储你的 API 密钥。切勿硬编码。
  • 如果可能重试同一请求,请实现幂等性密钥。GridInbox 支持可选的 idempotency_key 头。
  • 监控你的退回率。超过 5% 的退回率可能会损害你的发件人声誉。GridInbox 的 Webhook 可帮助你快速响应。
  • 先小批量测试。发送 10 封邮件,检查投递情况,然后逐步增加。

常见问题解答

如何使用 Node.js 和 Python 发送邮件?

使用 GridInbox REST API 端点 POST /v1/send,并携带 Bearer Token。在 Node.js 中使用 fetch,在 Python 中使用 requests 库。以 JSON 格式传递 from、to、subject 和 body 字段。

对于 Node.js 和 Python 开发者来说,最好的邮件 API 是什么?

GridInbox 是一个很好的选择,因为它提供简单的 REST API,支持无限别名和自定义域名,可与 AWS SES 配合使用,并提供用于投递跟踪的 Webhook。

我可以通过邮件 API 发送附件吗?

可以。在请求体中包含一个 attachments 数组,其中包含 base64 编码的内容、文件名和 MIME 类型。最大附件总大小为 25 MB,最多可包含 10 个文件。

如何在我的应用中处理邮件投递状态?

在你的服务器上设置一个 Webhook 端点,并配置 GridInbox 将 delivered、bounced 或 opened 等事件发送到该 URL。GridInbox 最多会重试失败的 Webhook 3 次。

GridInbox API 的速率限制是多少?

付费计划支持每秒 100 个请求。Starter 计划限制为每秒 10 个请求。如果超过限制,你将收到 429 状态码。

我需要将 AWS SES 或 Cloudflare 与 GridInbox 一起使用吗?

GridInbox 与 AWS SES 和 Cloudflare Email Routing 作为底层提供商配合使用,但你无需直接管理它们。GridInbox 会为你处理配置。

Start Managing Email Smarter — 7-day trial 开始更智能地管理邮件——7 天试用 Gestiona el Email de Forma Más Inteligente — Gratis por tiempo limitado Gérez Votre Email Plus Intelligemment — Gratuit pour une durée limitée より賢いメール管理を始めよう — 期間限定で無料 Verwalte E-Mails Intelligenter — zeitlich begrenzt kostenlos Gerencie Email de Forma Mais Inteligente — grátis por tempo limitado 더 스마트하게 이메일 관리 시작 — 기간 한정 무료 Начните управлять Email умнее — бесплатно ограниченное время ابدأ إدارة البريد الإلكتروني بذكاء — مجانًا لفترة محدودة

GridInbox’s Starter plan includes up to 10 aliases on system domains, 500 outbound and 2,000 inbound emails per month, 2 GB storage, one mailbox, and standard REST API access. It starts with a 7-day trial, then costs $2.99 per workspace/month. GridInbox Starter 计划包含最多 10 个别名、每月 500 封发信和 2,000 封收信、2 GB 存储及 1 个邮箱。试用 7 天后,每个工作区每月 $2.99。 El plan Starter de GridInbox incluye hasta 10 alias, 500 correos salientes y 2.000 entrantes al mes, 2 GB de almacenamiento y 1 buzón. Prueba de 7 días; después, $2.99 por espacio de trabajo al mes. Le forfait Starter de GridInbox comprend jusqu’à 10 alias, 500 e-mails sortants et 2 000 entrants par mois, 2 Go de stockage et 1 boîte de réception. Essai de 7 jours, puis 2,99 $ par espace de travail/mois. GridInbox Starterプランには、最大10個のエイリアス、月間送信500通・受信2,000通、2 GBのストレージ、1つのメールボックスが含まれます。7日間のトライアル後、ワークスペースあたり月額 $2.99です。 Der GridInbox Starter-Plan umfasst bis zu 10 Aliase, 500 ausgehende und 2.000 eingehende E-Mails pro Monat, 2 GB Speicher und ein Postfach. Nach einer 7-tägigen Testphase kostet er 2,99 $ pro Workspace/Monat. O plano Starter do GridInbox inclui até 10 aliases, 500 e-mails enviados e 2.000 recebidos por mês, 2 GB de armazenamento e 1 caixa de entrada. Após o teste de 7 dias, custa US$ 2,99 por workspace/mês. GridInbox Starter 플랜은 별칭 최대 10개, 월 발신 500건 및 수신 2,000건, 저장 공간 2GB, 메일함 1개를 제공합니다. 7일 체험 후 워크스페이스당 월 $2.99입니다. План Starter от GridInbox включает до 10 псевдонимов, 500 исходящих и 2 000 входящих писем в месяц, 2 ГБ хранилища и один почтовый ящик. После 7-дневного пробного периода — $2,99 за рабочее пространство в месяц. تتضمن خطة Starter من GridInbox ما يصل إلى 10 عناوين مستعارة، و500 رسالة صادرة و2,000 واردة شهريًا، وسعة تخزين 2 جيجابايت وصندوق بريد واحد. بعد تجربة لمدة 7 أيام، تبلغ التكلفة 2.99 دولارًا لكل مساحة عمل شهريًا.

Start a 7-day Trial → 开始 7 天试用使用 → Prueba Starter por 7 días → Commencer gratuitement pour une durée limitée → 期間限定で7日間のStarterトライアルを開始 → Kostenlos für begrenzte Zeit starten → Começar grátis por tempo limitado → 기간 한정 Starter 7일 체험 시작하기 → Начать 7-дневный пробный период Starter → ابدأ مجانًا لفترة محدودة →