SMTP Commands Reference
完整的SMTP命令、响应码和电子邮件协议流参考,包含交互式示例。
EHLOsessionEHLO <hostname>Extended greeting; identifies the client and requests ESMTP extensions.
EHLO mail.example.comHELOsessionHELO <hostname>Basic SMTP greeting. Use EHLO for modern servers.
HELO mail.example.comQUITsessionQUITClose the SMTP connection gracefully.
QUITSTARTTLSsessionSTARTTLSUpgrade the connection to TLS encryption.
STARTTLSNOOPsessionNOOPNo operation; used to keep the connection alive.
NOOPRSETsessionRSETAbort the current mail transaction and reset the session.
RSETAUTHauthAUTH <mechanism> [credentials]Authenticate the client to the server (PLAIN, LOGIN, CRAM-MD5).
AUTH LOGINMAIL FROMmessageMAIL FROM:<address>Specify the sender envelope address.
MAIL FROM:<sender@example.com>RCPT TOmessageRCPT TO:<address>Specify a recipient envelope address. Can be repeated.
RCPT TO:<recipient@example.com>DATAmessageDATABegin transmitting the message body. End with a line containing only a period.
DATAVRFYsessionVRFY <address>Verify that a mailbox exists (often disabled for security).
VRFY user@example.comEXPNsessionEXPN <list>Expand a mailing list (often disabled for security).
EXPN users关于此工具
SMTP(简单邮件传输协议)是邮件服务器在互联网上中继和投递电子邮件所使用的基于文本的协议。无论是集成邮件功能的开发者,还是排查邮件投递问题的系统管理员,都需要清楚掌握它的核心命令。
本参考列出了 HELO/EHLO、MAIL FROM、RCPT TO、DATA、STARTTLS、AUTH 和 QUIT 等关键 SMTP 命令,并附有各自的语法、简短说明和示例。你可以借助它通过 telnet 或 openssl 逐步走完一次手动会话,诊断邮件被拒收的原因,或者一步步学习该协议的工作方式。
请注意,现代邮件服务器几乎都要求使用 STARTTLS 进行加密,并要求 AUTH 进行发送身份验证,因此未加密的明文会话往往会被拒绝。请将本页面视为学习和参考的辅助工具,而非生产环境邮件配置的指南。
常见问题
代码实现
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
def send_email_smtp(
smtp_host: str,
smtp_port: int,
username: str,
password: str,
from_addr: str,
to_addr: str,
subject: str,
body: str,
use_tls: bool = True
) -> bool:
"""Send email using SMTP with manual command flow."""
try:
with smtplib.SMTP(smtp_host, smtp_port) as server:
server.ehlo() # EHLO command
if use_tls:
server.starttls() # STARTTLS command
server.ehlo() # Re-EHLO after TLS
server.login(username, password) # AUTH command
msg = MIMEMultipart()
msg['From'] = from_addr
msg['To'] = to_addr
msg['Subject'] = subject
msg.attach(MIMEText(body, 'plain'))
# MAIL FROM, RCPT TO, DATA commands
server.sendmail(from_addr, to_addr, msg.as_string())
return True
except smtplib.SMTPException as e:
print(f"SMTP Error: {e}")
return False
# Test SMTP connection manually
def test_smtp_connection(host: str, port: int) -> dict:
import socket
try:
with smtplib.SMTP(host, port, timeout=5) as server:
banner = server.getwelcome()
ehlo_resp = server.ehlo()
return {
"connected": True,
"banner": banner.decode(),
"extensions": list(server.esmtp_features.keys())
}
except Exception as e:
return {"connected": False, "error": str(e)}
result = test_smtp_connection("smtp.gmail.com", 587)
print(result)Comments & Feedback
Comments are powered by Giscus. Sign in with GitHub to leave a comment.