簡體   English   中英

如何在Python中將pdf文件附加到MIME電子郵件中?

[英]How to attach a pdf file to a MIME email in Python?

我正在制作一個自動郵件發送程序(在Python 3.6.1中)用於電子郵件營銷。 我有附加PDF文件的問題。 PDF文件的文件名和頁數在郵件中是正確的,但PDF文件總是空白,其大小增加。我嘗試了三種不同的方式,另外兩種方法不起作用。 最后,我決定在這里問。 謝謝你的幫助。

message = MIMEMultipart()
message['Subject'] = "Attachment Test"
message['From'] = 'myemail'
message['Reply-to'] = 'myemail'
message['To'] = 'otheremail'

text = MIMEText("Message Body")
message.attach(text)

directory = "C:\ExamplePDF.pdf"
with open(directory, encoding = 'utf-8', errors = 'replace') as opened:
    openedfile = opened.read()
attachedfile = MIMEApplication(openedfile, _subtype = "pdf", _encoder = encode_base64)
attachedfile.add_header('content-disposition', 'attachment', filename = "ExamplePDF.pdf")
message.attach(attachedfile)

server = SMTP("smtp.gmail.com:587")
server.ehlo()
server.starttls()
server.login("myemail", "password")
server.sendmail(message['From'], message['To'], message.as_string())
server.quit()

(答案來自評論)
以二進制模式閱讀PDF:
with open("file.pdf", "rb") as opened:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM