使用Python在HTML电子邮件中发送附件

问题描述 投票:5回答:1

我看到堆栈溢出已经有一些类似的问题,但我无法找到解决我的具体问题的方法。

我正在尝试使用Python发送带有.pdf附件的HTML电子邮件。当我在gmail.com检查我的电子邮件时似乎工作正常,但是当我通过苹果邮件程序查看邮件时,我看不到附件。知道是什么导致了这个吗?

我的代码如下。很多都是从堆栈溢出的各个地方复制的,所以我不完全理解每个部分正在做什么,但它似乎(大多数)工作:

import smtplib  
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText                    
from email.mime.application import MIMEApplication
from os.path import basename
import email
import email.mime.application

#plain text version
text = "This is the plain text version."

#html body
html = """<html><p>This is some HTML</p></html>"""

# Create message container - the correct MIME type is multipart/alternative.
msg = MIMEMultipart('alternative')
msg['Subject'] = "Deliverability Report"
msg['From'] = "[email protected]"
msg['To'] = "[email protected]"

# Record the MIME types of both parts - text/plain and text/html
part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')

# create PDF attachment
filename='graph.pdf'
fp=open(filename,'rb')
att = email.mime.application.MIMEApplication(fp.read(),_subtype="pdf")
fp.close()
att.add_header('Content-Disposition','attachment',filename=filename)

# Attach parts into message container.
msg.attach(att)
msg.attach(part1)
msg.attach(part2)

# Send the message via local SMTP server.
s = smtplib.SMTP()
s.connect('smtp.webfaction.com')
s.login('NAME','PASSWORD')
s.sendmail(msg['From'], msg['To'], msg.as_string())
s.quit()

我不确定它是否相关,但我在WebFaction服务器上运行此代码。

谢谢您的帮助!

python html email email-attachments
1个回答
0
投票

使用

msg = MIMEMultipart('mixed')

而不是'替代'

© www.soinside.com 2019 - 2024. All rights reserved.