Python 3 高级编程 – 使用 SMTP 发送电子邮件

简单邮件传输协议 (SMTP) 是一种处理在邮件服务器之间发送电子邮件和路由电子邮件的协议。Python 提供了 smtplib 模块,它定义了一个 SMTP 客户端会话对象,可用于将邮件发送到任何具有 SMTP 或 ESMTP 侦听器守护程序的 Internet 机器。创建一个 SMTP 对象的简单语法:

import smtplib smtpObj = smtplib.SMTP( [host [, port [, local_hostname]]] )

参数说明:

  • host – 这是运行 SMTP 服务器的主机。可以指定主机的 IP 地址或域名,例如 baidu.com。这是一个可选参数。
  • 端口 – 如果提供主机参数,那么需要指定一个端口,SMTP 服务器正在侦听。通常此端口为 25。
  • local_hostname – 如果 SMTP 服务器在本地机器上运行,那么可以只指定 localhost 选项。

SMTP 对象有一个名为 sendmail 的实例方法,它通常用于执行邮寄消息的工作。它需要三个参数:

  • The sender – 带有发件人地址的字符串。
  • The receivers – 字符串列表,每个接收者一个。
  • The message – 作为字符串的消息,其格式在各种 RFC 中指定。

例如,使用 Python 脚本发送一封电子邮件的简单方法。尝试一次:

import smtplib sender = '[email protected]' #发送方 receivers = ['[email protected]'] #接收方 #发送消息 message = """From: From Person <[email protected]> To: To Person <[email protected]> Subject: SMTP e-mail test This is a test e-mail message. """ try: smtpObj = smtplib.SMTP('localhost') smtpObj.sendmail(sender, receivers, message) print "Successfully sent email" except SMTPException: print "Error: unable to send email"

例子中,在消息中放置了一个基本的电子邮件,使用三重引号,注意正确格式化标题。电子邮件需要 From、To 和 Subject 标头,并用空行与电子邮件正文分隔。

要发送邮件,可以使用 smtpObj 连接到本地机器上的 SMTP 服务器。然后使用 sendmail 方法以及消息、发件人地址和目标地址作为参数(即使发件人和收件人地址在电子邮件本身中,但并不总是用于路由邮件)。

如果没有在本地计算机上运行 SMTP 服务器,则可以使用 smtplib 客户端与远程 SMTP 服务器通信。除非使用的是网络邮件服务(例如 gmail 或 Yahoo! Mail),否则您的电子邮件提供商必须提供可以外发邮件服务器详细信息,例如:

mail = smtplib.SMTP('smtp.gmail.com', 587)

使用 Python 发送 HTML 电子邮件

当使用 Python 发送文本消息时,所有内容都被视为简单文本。即使在文本消息中包含 HTML 标记,它也会显示为简单文本,并且 HTML 标记不会根据 HTML 语法进行格式化。但是,Python 提供了将 HTML 消息作为实际 HTML 消息发送的选项。

发送电子邮件时,可以指定 Mime 版本、内容类型和字符集以发送 HTML 电子邮件。

例如,将 HTML 内容作为电子邮件发送。

import smtplib message = """From: From Person <[email protected]> To: To Person <[email protected]> MIME-Version: 1.0 Content-type: text/html Subject: SMTP HTML e-mail test This is an e-mail message to be sent in HTML format <b>This is HTML message.</b> <h1>This is headline.</h1> """ try: smtpObj = smtplib.SMTP('localhost') smtpObj.sendmail(sender, receivers, message) print "Successfully sent email" except SMTPException: print "Error: unable to send email"

发送带附件电子邮件中

要发送包含混合内容的电子邮件,需要将 Content-type 标头设置为 multipart/mixed。然后,可以在边界内指定文本和附件部分。

边界以两个连字符开头,后跟一个唯一编号,该编号不能出现在电子邮件的消息部分。表示电子邮件最后部分的最后边界也必须以两个连字符结尾。

附件应使用 pack("m") 函数进行编码,以便在传输前具有 base 64 编码。

例如,将文件 /tmp/test.txt 作为附件发送:

import smtplib import base64 filename = "/tmp/test.txt" # Read a file and encode it into base64 format fo = open(filename, "rb") filecontent = fo.read() encodedcontent = base64.b64encode(filecontent) # base64 sender = '[email protected]' #发送方 receivers = ['[email protected]'] #接收方 marker = "AUNIQUEMARKER" body =""" This is a test email to send an attachement. """ # Define the main headers. part1 = """From: From Person <[email protected]> To: To Person <[email protected]> Subject: Sending Attachement MIME-Version: 1.0 Content-Type: multipart/mixed; boundary=%s --%s """ % (marker, marker) # Define the message action part2 = """Content-Type: text/plain Content-Transfer-Encoding:8bit %s --%s """ % (body,marker) # Define the attachment section part3 = """Content-Type: multipart/mixed; name=\"%s\" Content-Transfer-Encoding:base64 Content-Disposition: attachment; filename=%s %s --%s-- """ %(filename, filename, encodedcontent, marker) message = part1 + part2 + part3 try: smtpObj = smtplib.SMTP('localhost') smtpObj.sendmail(sender, reciever, message) print "Successfully sent email" except Exception: print ("Error: unable to send email")

在 HTML 文本中添加图片

 import smtplib from email.mime.image import MIMEImage from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.header import Header sender = '[email protected]' #发送方 receivers = ['[email protected]'] #接收方 msgRoot = MIMEMultipart('related') msgRoot['From'] = Header("header", 'utf-8') msgRoot['To'] = Header("receipts", 'utf-8') subject = 'Python SMTP sendding email' msgRoot['Subject'] = Header(subject, 'utf-8') msgAlternative = MIMEMultipart('alternative') msgRoot.attach(msgAlternative) mail_msg = """ <p>Python 邮件发送测试...</p> <p><a href="http://www.baidu.com">百度</a></p> <p>图片演示:</p> <p><img decoding="async" src="cid:image1"></p> """ msgAlternative.attach(MIMEText(mail_msg, 'html', 'utf-8')) # 指定图片为当前目录 fp = open('test.png', 'rb') msgImage = MIMEImage(fp.read()) fp.close() # 定义图片 ID,在 HTML 文本中引用 msgImage.add_header('Content-ID', '<image1>') msgRoot.attach(msgImage) try: smtpObj = smtplib.SMTP('localhost') smtpObj.sendmail(sender, receivers, msgRoot.as_string()) print "邮件发送成功" except smtplib.SMTPException: print "Error: 无法发送邮件" 

发表回复

您的邮箱地址不会被公开。必填项已用 * 标注