I am making an automatic mail sending program (in Python 3.6.1) to use in email marketing. I am having an issue attaching PDF file. File name and page count of PDF file is correct in the mail but PDF file is always blank and its size increases.I tried three different ways, the other two ways didn't work. Last resort I decided to ask it here. Thanks for your help.
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()
(Answer taken from comment)
Read your PDF in binary mode:
with open("file.pdf", "rb") as opened: