有人能指出以下代码的错误吗?
我尝试使用Python发送多部分电子邮件。我可以显示电子邮件正文,但PDF显示为空白。
我可以收到一封只有一个正常工作的电子邮件,或者只有一个PDF的电子邮件,但是在一起,它不会起作用。
s = smtplib.SMTP('smtp.gmail.com',587)
s.starttls()
s.ehlo
try:
s.login(gmail, password)
except:
print 'SMTPAuthenticationError'
fp = file(attachment_path)
pdfAttachment = MIMEApplication(fp.read(), _subtype = "pdf", _encoder=encoders.encode_base64)
pdfAttachment.add_header('content-disposition', 'attachment', filename = ('utf-8', '', basename(attachment_path)))
text = MIMEMultipart('alternative')
t = open(email_body_path).read()
text.attach(MIMEText(t, "plain", _charset="utf-8"))
message = MIMEMultipart('mixed')
message.attach(text)
message.attach(pdfAttachment)
message['Subject'] = 'Test multipart message'
s.sendmail(gmail, 'me@gmail.com', message.as_string())
s.close()
答案 0 :(得分:2)
我认为你可能会让事情变得复杂。 multipart/alternative
旨在用于相同数据的不同表示,例如HTML的纯文本版本的消息和相同的消息。在您的情况下,您只需创建一个multipart/mixed
并附上文本和pdf消息。
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
with open(attachment_path) as pdf_file, open(email_body_path) as text_file:
pdf = MIMEApplication(pdf_file.read(), _subtype = 'pdf')
pdf.add_header('content-disposition', 'attachment', filename=basename(attachment_path))
text = MIMEText(text_file.read(), _charset='UTF-8')
msg = MIMEMultipart(_subparts=(text, pdf))
msg['Subject'] = 'Test multipart message'
这将创建如下所示的消息:
>>> print msg
From nobody Tue Mar 3 16:35:45 2015
Content-Type: multipart/mixed; boundary="===============4785752000147824692=="
MIME-Version: 1.0
Subject: Test multipart message
--===============4785752000147824692==
MIME-Version: 1.0
Content-Type: text/plain; charset="utf-8"
Content-Transfer-Encoding: base64
VGhpcyBpcyB0aGUgZW1haWwgdGV4dCBib2R5LgpBbmQgdGhlcmUgaXMgYW4gYXR0YWNoZWQgUERG
Lgo=
--===============4785752000147824692==
Content-Type: application/pdf
MIME-Version: 1.0
Content-Transfer-Encoding: base64
content-disposition: attachment; filename="quickref.pdf"
JVBERi0xLjQKJcfsj6IKNiAwIG9iago8PC9MZW5ndGggNyAwIFIvRmlsdGVyIC9GbGF0ZURlY29k
ZT4+CnN0cmVhbQp4nOVbSXMctxW+T+We6xxnkkwb+3KUY9lVTizHFm1XyuUDTUk0o6Eka2Hik/56
.
.
.
--===============4785752000147824692==--
答案 1 :(得分:1)
我有类似的问题。问题是当你在python中打开一个文件时,它以人类可读的形式读取(即接口库试图解码信息并以可编辑的形式呈现它)。 但我们无法使用python以他的方式阅读和解码pdf。因此,要附加您的pdf文件,请将其打开为字节可读:
fp = open(attachment_path,'rb')
现在,当您执行以下操作时,您将以机器可读格式读取该文件(因为它存储在磁盘上,而不会尝试对其进行解码)。这会将您的文件原样附加到邮件中。这解决了我的问题。这是我的文件附件代码的完整片段
attachment_path = "FILENAME.pdf"
fp = open(attachment_path,'rb')
x = fp.read()
fp.close()
fileMsg = email.mime.base.MIMEBase('application','pdf')
fileMsg.set_payload(x)
email.encoders.encode_base64(fileMsg)
fileMsg.add_header('Content-Disposition','attachment;filename=FILENAME.pdf')
希望这会有所帮助:)