如何使用Python电子邮件模块在电子邮件中发送文件?

时间:2017-03-26 10:48:33

标签: python file email

我听说,您可以使用电子邮件模块发送每封电子邮件的文件。我该怎么做?

2 个答案:

答案 0 :(得分:1)

看看:Here

来自网站的

示例

# Import smtplib for the actual sending function
import smtplib

# Here are the email package modules we'll need
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart

COMMASPACE = ', '

# Create the container (outer) email message.
msg = MIMEMultipart()
msg['Subject'] = 'Our family reunion'
# me == the sender's email address
# family = the list of all recipients' email addresses
msg['From'] = me
msg['To'] = COMMASPACE.join(family)
msg.preamble = 'Our family reunion'

# Assume we know that the image files are all in PNG format
for file in pngfiles:
    # Open the files in binary mode.  Let the MIMEImage class 
    automatically
    # guess the specific image type.
    fp = open(file, 'rb')
    img = MIMEImage(fp.read())
    fp.close()
    msg.attach(img)

# Send the email via our own SMTP server.
s = smtplib.SMTP('localhost')
s.sendmail(me, family, msg.as_string())
s.quit()

答案 1 :(得分:1)

鉴于您已经创建了一个多部分:

msg = MIMEMultipart()

然后您可以通过执行以下操作添加图像:

filename = "..."
with open(filename, "rb") as f:
    attachment = MIMEImage(f.read())

或者您可以通过执行以下操作将字符串"Hello World"添加为test.txt

filename = "test.txt"
attachment = MIMEText("Hello World")

对于二进制文件或一般情况下,您可以这样做:

filename = "..."
ctype, encoding = mimetypes.guess_type(filename)
maintype, subtype = ctype.split("/", 1)
attachment = MIMEBase(maintype, subtype)
with open(filename, "rb") as f:
    attachment.set_payload(f.read())
encoders.encode_base64(attachment)

请记住from email import encoders

最后,您可以执行以下操作将其添加到电子邮件中:

attachment.add_header("Content-Disposition", "attachment", filename=filename)
msg.attach(attachment)

要记住的一件重要事情是,必须首先添加所有文件。消息必须才能符合RFC 2046,这符合以下要求:

  

接收用户代理应该选择并显示他们能够显示的最后一种格式。