Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to attach a pdf file to a MIME email in Python?

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()
like image 494
SamIsc Avatar asked Jun 06 '17 10:06

SamIsc


People also ask

Can Python send an email with attachment?

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.

Can Python work with PDF files?

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.

Can you scrape data from a PDF Python?

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.


1 Answers

(Answer taken from comment)
Read your PDF in binary mode:
with open("file.pdf", "rb") as opened:

like image 94
SamIsc Avatar answered Oct 14 '22 13:10

SamIsc