Skip to content

非公式本サイトは非公式の日本語ドキュメントであり、Cloudflare 公式サイトではありません。最新情報はdevelopers.cloudflare.comをご確認ください。

SMTP でメールを送信する

curl、Nodemailer、Python smtplib、PHPMailer を使い、Cloudflare Email Service の SMTP でトランザクションメールを送信します。

最終更新 Markdown で表示Agent セットアップ

任意の SMTP 対応言語またはクライアントから、Cloudflare Email Service の 認証済み SMTPsmtp.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 用にオンボードされている必要があります。

Nodemailernpm install 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 エンコードした添付ファイルを含む)は 5 MiB 以下である必要があります。制限 を参照してください。

エラー処理

Nodemailer は、.responseCode に SMTP 応答コードが入った Error で Promise を拒否します。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 で implicit TLS 接続を開きます。Cloudflare の SMTP エンドポイントが求める方式です。smtplib.SMTPstarttls() は使わないでください。STARTTLS はサポートされていません。

複数の受信者に送信する

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

1 つの SMTP セッションで届けられる RCPT TO アドレスは最大 50 件です。制限 を参照してください。

添付ファイル付きで送信する

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 は、SMTP 応答コード付きの smtplib.SMTPException のサブクラスを送出します。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、名前付きアドレス。
  • 制限 — アカウント、メッセージ、セッションの制限。

役に立ちましたか?