1
我正在製作一個用於電子郵件營銷的自動郵件發送程序(使用Python 3.6.1)。我有一個附加PDF文件的問題。 PDF文件的文件名和頁數在郵件中是正確的,但PDF文件總是空白並且其大小增加。我嘗試了三種不同的方式,其他兩種方式都不起作用。我最後決定在這裏問一下。謝謝你的幫助。如何將pdf文件附加到Python中的MIME郵件?
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的二進制模式:'開放( 「file.pdf」, 「RB」)作爲打開:'... – zwer
非常感謝你,這工作! – SamIsc
您可以將此添加爲答案,並將其標記爲已被其他人接受,以便於查找。 – bastelflp