使用 Python 将附件作为电子邮件发送

pythonserver side programmingprogramming更新于 2025/5/7 6:04:17

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

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

附加文件应使用 pack("m") 函数进行编码,以便在传输前进行 base64 编码。

示例

以下是将文件 /tmp/test.txt 作为附件发送的示例。试一次 −

#!/usr/bin/python
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 = 'webmaster@tutorialpoint.com'
reciever = 'amrood.admin@gmail.com'
marker = "AUNIQUEMARKER"
body ="""
This is a test email to send an attachement.
"""
# Define the main headers.
part1 = """From: From Person <me@fromdomain.net>
To: To Person <amrood.admin@gmail.com>
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"

相关文章


有用资源