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()
Use Python's built-in smtplib library to send basic emails. Send emails with HTML content and attachments using the email package. Send multiple personalized emails using a CSV file with contact data.
You can work with a preexisting PDF in Python by using the PyPDF2 package. PyPDF2 is a pure-Python package that you can use for many different types of PDF operations.
With the help of python libraries, we can save time and money by automating this process of scraping data from PDF files and converting unstructured data into panel data.
(Answer taken from comment)
Read your PDF in binary mode:with open("file.pdf", "rb") as opened:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With