返回邮件
通过代码发送
Send mail from your application using any SMTP library. We show the Node.js / nodemailer flow because it's the most common - every other language uses the exact same fields.
安装节点邮件程序
terminal
npm install nodemailer
# or
pnpm add nodemailer
# or
bun add nodemailer最小转运蛋白
mailer.ts
import nodemailer from "nodemailer";
export const transporter = nodemailer.createTransport({
host: process.env.SMTP_HOST!, // smtp host from the right rail
port: Number(process.env.SMTP_PORT), // 587
secure: false, // STARTTLS upgrades after connect
requireTLS: true, // refuse if TLS upgrade is unavailable
auth: {
user: process.env.SMTP_USER!, // your full email address
pass: process.env.SMTP_PASS!, // postmaster password - keep in .env
},
});为什么端口 587 + STARTTLS 而不是 465 + secure: true? 两者都有效。 587/STARTTLS 是现代提交标准,也是大多数客户选择的标准。 465(隐式 TLS)也受支持 - 设置
port: 465, secure: true 并删除 requireTLS.发送消息
send.ts
import { transporter } from "./mailer";
await transporter.sendMail({
from: '"Your App" <[email protected]>',
to: "[email protected]",
subject: "Hello from your self-hosted mail server",
text: "Plain-text body.",
html: "<p>HTML body too - clients pick whichever they prefer.</p>",
});首先验证连接
启动时,对服务器执行 ping 操作,以便损坏的配置快速失败,而不是等待第一个 sendMail 超时:
boot.ts
await transporter.verify();
console.log("SMTP ready");来自其他语言
各个库的形状是相同的 - 主机、端口、TLS 模式、用户名、密码。
python · smtplib
import smtplib
from email.message import EmailMessage
msg = EmailMessage()
msg["From"] = "[email protected]"
msg["To"] = "[email protected]"
msg["Subject"] = "Hello"
msg.set_content("Plain text body")
with smtplib.SMTP("smtp.yourdomain.com", 587) as s:
s.starttls()
s.login("[email protected]", "PASSWORD")
s.send_message(msg)go · net/smtp
auth := smtp.PlainAuth("",
"[email protected]",
"PASSWORD",
"smtp.yourdomain.com",
)
err := smtp.SendMail(
"smtp.yourdomain.com:587",
auth,
"[email protected]",
[]string{"[email protected]"},
[]byte("Subject: Hello\r\n\r\nbody"),
)生产清单
- 1切勿提交密码。使用 环境变量 在运行时加载(Vercel/Railway/Fly 均执行此操作;本地使用
.env.local). - 2留个单 转运者 进程生命周期内的实例 - 每封电子邮件打开一个新的 TCP+TLS 握手会杀死吞吐量。
- 3设置 来自 该服务器上存在的邮箱的地址。外部发件人地址被您的 SPF + DMARC 策略拒绝。
- 4对于交易量,运行 验证() 在启动时并添加重试 发送邮件;短暂的网络故障是正常的。
- 5如果邮件停止发送,请检查您的 OpenShip 管理员中的“运行状况”选项卡 - 出站队列位于此处。