Ruby 发送邮件(Net::SMTP)
讲解 SMTP 邮件传输协议基础、Ruby Net::SMTP 的 new/start/send_message/sendmail 参数用法、纯文本与 HTML MIME 邮件构造以及基于 multipart/mixed 和 pack('m') Base64 编码的附件发送。
学完这一章,你能够
- 讲解 SMTP 邮件传输协议基础、Ruby Net::SMTP 的 new/start/send_message/sendmail 参数用法、纯文本与 HTML MIME 邮件构造以及基于 multipart/mixed 和 pack('m') Base64 编码的附件发送。
SMTP 协议基础与 Net::SMTP 核心方法
SMTP(Simple Mail Transfer Protocol,简单邮件传输协议)规定了邮件从发件端向收件端中转递送的通信规范。Ruby 通过 `net/smtp`(Ruby 3.1+ 起作为 bundled gem 提供)中的 `Net::SMTP` 类发送邮件,主要提供两类入口:`Net::SMTP.new(server = 'localhost', port = 25)` 仅创建客户端对象;`Net::SMTP.start(server, port, domain, account, password, authtype)` 则自动完成建立连接、HELO/EHLO 握手与认证(`domain` 默认 `ENV['HOSTNAME']` 或 `'localhost'`,`account`/`password` 默认 `nil`,`authtype` 支持 `:plain`、`:login`、`:cram_md5`),配合代码块使用时在块结束后自动关闭会话。在连接内通过 `send_message` 或别名 `sendmail(source, sender, recipients)` 投递报文,其中 `source` 为完整邮件字符串或可迭代数据源,`sender` 为信封发件人地址,`recipients` 为单个收件人地址或地址数组。
发送纯文本邮件与远程认证连接
构造一封合规的 RFC 5322 纯文本邮件,必须包含 `From`、`To`、`Subject` 等头部字段,并在头部与正文之间严格留出一个**空行**分隔(例如借助 Ruby Here-Document `<<MESSAGE_END`)。若本机未部署 MTA 邮件服务器,可将 `Net::SMTP.start` 指向远程 SMTP 主机(如 `mail.your-domain.com`),并传入端口、发件域名、用户名、密码及认证方式 `:plain`(现代公网邮件服务通常要求 587/465 端口配合 `enable_starttls_auto` 或 `enable_tls` 加密传输)。
发送 HTML 邮件与带 Base64 附件的多部分邮件
要发送富文本 HTML 邮件,只需在邮件头部显式声明 `MIME-Version: 1.0` 和 `Content-Type: text/html; charset=UTF-8`,并在空行后写入 HTML 标签正文即可由客户端按网页格式渲染。
发送携带附件的混合邮件时,顶层 `Content-Type` 必须设置为 `multipart/mixed; boundary=边界标识`,随后按 `--边界标识` 分隔正文段(`text/plain`)与附件段,并以 `--边界标识--` 结束。附件原始内容须通过 `[filecontent].pack("m")`(或 `Base64.encode64`)转为 Base64 编码,并在附件段头声明 `Content-Transfer-Encoding: base64` 与 `Content-Disposition: attachment; filename="..."`(附件段自身的 `Content-Type` 推荐使用 `application/octet-stream` 或具体文件 MIME 类型,且与顶层头部之间须有空行)。同时需注意 `rescue => e` 打印异常时应写 `e.message` 或 `#{e}`,避免字符串与 `Exception` 对象直接用 `+` 拼接报 `TypeError`;群发给多个收件人时在 `recipients` 数组中以逗号分隔多个地址即可。
离线校验 Ruby SMTP 纯文本、HTML MIME 与 multipart/mixed Base64 附件报文
展开查看收起
"""Offline Ruby 3.x semantic verification lab for Chapter 39 (sending-email)."""
import base64
from email import message_from_string
import json
VERSION = "CPython 3.12.14 offline Ruby 3.x semantic verifier (MRI ruby absent, no live SMTP)"
def case_smtp_config_and_plain_message():
raw_plain = (
"From: Private Person <me@example.com>\r\n"
"To: A Test User <test@example.com>\r\n"
"Subject: SMTP e-mail test\r\n"
"\r\n"
"This is a test e-mail message.\r\n"
)
msg = message_from_string(raw_plain)
defaults = {"server": "localhost", "port": 25, "authtypes": ["plain", "login", "cram_md5"]}
expected = {
"default_port": 25,
"from": "Private Person <me@example.com>",
"to": "A Test User <test@example.com>",
"subject": "SMTP e-mail test",
"body": "This is a test e-mail message.",
"has_blank_line_sep": True,
"supported_auth_count": 3,
}
actual = {
"default_port": defaults["port"],
"from": msg["From"],
"to": msg["To"],
"subject": msg["Subject"],
"body": msg.get_payload().strip(),
"has_blank_line_sep": "\r\n\r\n" in raw_plain,
"supported_auth_count": len(defaults["authtypes"]),
}
return {
"name": "smtp_config_and_plain_message",
"summary": "核验 Net::SMTP 默认连接参数、认证方式及纯文本邮件 RFC 5322 头体空行分隔解析",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_smtp_html_mime_message():
raw_html = (
"From: Private Person <me@example.com>\r\n"
"To: A Test User <test@example.com>\r\n"
"MIME-Version: 1.0\r\n"
"Content-Type: text/html; charset=UTF-8\r\n"
"Subject: SMTP HTML test\r\n"
"\r\n"
"<b>This is HTML message.</b>\r\n"
"<h1>This is headline.</h1>\r\n"
)
msg = message_from_string(raw_html)
expected = {
"mime_version": "1.0",
"content_type": "text/html",
"charset": "utf-8",
"has_h1": True,
}
actual = {
"mime_version": msg["MIME-Version"],
"content_type": msg.get_content_type(),
"charset": msg.get_content_charset(),
"has_h1": "<h1>This is headline.</h1>" in msg.get_payload(),
}
return {
"name": "smtp_html_mime_message",
"summary": "核验 HTML 邮件中 MIME-Version、Content-Type 与 UTF-8 字符集声明及正文解析",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_smtp_multipart_base64_attachment():
marker = "AUNIQUEMARKER"
file_bytes = b"Ruby SMTP attachment sample.\n"
# Equivalent to Ruby [filecontent].pack("m")
encoded = base64.encodebytes(file_bytes).decode("ascii")
raw_multipart = (
f"From: Private Person <me@example.com>\r\n"
f"To: A Test User <test@example.com>\r\n"
f"Subject: Sending Attachment\r\n"
f"MIME-Version: 1.0\r\n"
f"Content-Type: multipart/mixed; boundary={marker}\r\n"
f"\r\n"
f"--{marker}\r\n"
f"Content-Type: text/plain; charset=UTF-8\r\n"
f"Content-Transfer-Encoding: 8bit\r\n"
f"\r\n"
f"This is a test email to send an attachment.\r\n"
f"--{marker}\r\n"
f'Content-Type: application/octet-stream; name="test.txt"\r\n'
f"Content-Transfer-Encoding: base64\r\n"
f'Content-Disposition: attachment; filename="test.txt"\r\n'
f"\r\n"
f"{encoded}"
f"--{marker}--\r\n"
)
msg = message_from_string(raw_multipart)
parts = msg.get_payload()
decoded_att = parts[1].get_payload(decode=True)
expected = {
"is_multipart": True,
"part_count": 2,
"part0_type": "text/plain",
"part1_filename": "test.txt",
"attachment_roundtrip": "Ruby SMTP attachment sample.\n",
}
actual = {
"is_multipart": msg.is_multipart(),
"part_count": len(parts),
"part0_type": parts[0].get_content_type(),
"part1_filename": parts[1].get_filename(),
"attachment_roundtrip": decoded_att.decode("utf-8"),
}
return {
"name": "smtp_multipart_base64_attachment",
"summary": "核验 multipart/mixed 边界分割、pack('m') 等价 Base64 编码与附件解码往返一致",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_smtp_config_and_plain_message(),
case_smtp_html_mime_message(),
case_smtp_multipart_base64_attachment(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
RFC 5322 与 MIME 规范以连续换行(空行)作为邮件头部与邮件正文的唯一分界线;缺少空行会导致正文被错误解析为邮件头或造成报文格式损坏。