跳转到内容
本站为社区维护的非官方中文翻译,与 Cloudflare, Inc. 无关联。本站不提供账户登录,请勿在任何非官方站点输入您的 Cloudflare 账户信息。官方文档:developers.cloudflare.com

通过 SMTP 发送邮件

Send transactional emails over Cloudflare Email Service SMTP using curl, Nodemailer, Python smtplib, or PHPMailer.

最后更新 查看 MarkdownAgent 设置

使用任意支持 SMTP 的语言或客户端,通过 Cloudflare Email Service 已认证 SMTP(smtp.mx.cloudflare.net:465)发送事务性邮件。

前提条件

  • 已为 Email Sending 接入域名。
  • 具有 Email Sending: Edit 权限的 Cloudflare API 令牌。请在环境中将其设为 CF_API_TOKEN。该令牌用作 SMTP 密码;用户名为字面字符串 api_token。

发送邮件

cat > mail.txt <<EOF
From: [email protected]
To: [email protected]
Subject: Welcome to our service!

Thanks for signing up.
EOF

curl --ssl-reqd \
  --url "smtps://smtp.mx.cloudflare.net:465" \
  --user "api_token:$CF_API_TOKEN" \
  --mail-from "[email protected]" \
  --mail-rcpt "[email protected]" \
  --upload-file mail.txt

发件人域名必须已在拥有该 API 令牌的账户上为 Email Sending 接入。

使用 npm install nodemailer 安装 Nodemailer ↗。

发送邮件

import nodemailer from "nodemailer";

const transporter = nodemailer.createTransport({
    host: "smtp.mx.cloudflare.net",
    port: 465,
    secure: true, // implicit TLS
    auth: {
        user: "api_token",
        pass: process.env.CF_API_TOKEN,
    },
});

const info = await transporter.sendMail({
    from: '"Acme" <[email protected]>',
    to: "[email protected]",
    subject: "Welcome to Acme",
    text: "Thanks for signing up.",
    html: "<h1>Welcome to Acme</h1><p>Thanks for signing up.</p>",
});

console.log("Message sent:", info.messageId);

发送带附件的邮件

const info = await transporter.sendMail({
    from: '"Acme Billing" <[email protected]>',
    to: "[email protected]",
    subject: "Your invoice",
    text: "Please find your invoice attached.",
    attachments: [
        {
            filename: "invoice-2026-04.pdf",
            path: "./invoices/invoice-2026-04.pdf",
            contentType: "application/pdf",
        },
    ],
});

邮件总大小(包括 base64 编码的附件)不得超过 25 MiB。请参阅限制。

错误处理

Nodemailer 会以 Error 拒绝 promise,其 .responseCode 反映 SMTP 响应码。请参阅 SMTP 响应码 与故障排除。

try {
    await transporter.sendMail({
        /* ... */
    });
} catch (err) {
    console.error(err.responseCode, err.message);
}

使用标准库 smtplib ↗(Python 3.8 或更高版本)。

发送邮件

import os
import smtplib
from email.message import EmailMessage

msg = EmailMessage()
msg["From"] = "Acme <[email protected]>"
msg["To"] = "[email protected]"
msg["Subject"] = "Welcome to Acme"
msg.set_content("Thanks for signing up.")
msg.add_alternative(
    "<h1>Welcome to Acme</h1><p>Thanks for signing up.</p>",
    subtype="html",
)

with smtplib.SMTP_SSL("smtp.mx.cloudflare.net", 465) as s:
    s.login("api_token", os.environ["CF_API_TOKEN"])
    s.send_message(msg)

smtplib.SMTP_SSL 会在端口 465 上打开隐式 TLS 连接,这是 Cloudflare SMTP 端点所要求的。请勿使用带 starttls() 的 smtplib.SMTP;不支持 STARTTLS。

发送给多个收件人

msg["To"] = ", ".join([
    "[email protected]",
    "[email protected]",
    "[email protected]",
])

单个 SMTP 会话最多可投递 50 个 RCPT TO 地址。请参阅限制。

发送带附件的邮件

from pathlib import Path

pdf = Path("invoice-2026-04.pdf").read_bytes()
msg.add_attachment(
    pdf,
    maintype="application",
    subtype="pdf",
    filename="invoice-2026-04.pdf",
)

错误处理

smtplib 会抛出 smtplib.SMTPException 的子类,并附带 SMTP 响应码。请参阅 SMTP 响应码 与故障排除。

try:
    with smtplib.SMTP_SSL("smtp.mx.cloudflare.net", 465) as s:
        s.login("api_token", os.environ["CF_API_TOKEN"])
        s.send_message(msg)
except smtplib.SMTPAuthenticationError as e:
    print(f"Auth failed: {e.smtp_code} {e.smtp_error!r}")
except smtplib.SMTPResponseException as e:
    print(f"SMTP error: {e.smtp_code} {e.smtp_error!r}")

发送邮件

<?php
use PHPMailer\PHPMailer\PHPMailer;

require 'vendor/autoload.php';

$mail = new PHPMailer(true);
$mail->isSMTP();
$mail->Host       = 'smtp.mx.cloudflare.net';
$mail->Port       = 465;
$mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
$mail->SMTPAuth   = true;
$mail->Username   = 'api_token';
$mail->Password   = getenv('CF_API_TOKEN');

$mail->setFrom('[email protected]', 'Acme');
$mail->addAddress('[email protected]');
$mail->Subject = 'Welcome to our service!';
$mail->Body    = 'Thanks for signing up.';
$mail->send();

后续步骤

  • SMTP 参考 — 连接详情、身份验证、响应码与故障排除。
  • 指定收件人 — 多个收件人、CC 与 BCC,以及命名地址。
  • 限制 — 账户、消息与会话限制。

这篇文档对您有帮助吗?