0

The code below sends an email with both text and image. I am trying to convert this email (text and images)to a pdf file and download the file to a specific path. Is there a way to convert this to pdf?

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage

strFrom = 'abc@outlook.com'
strTo = 'xyz@outlook.com'

msgRoot = MIMEMultipart('related')
msgRoot['Subject'] = 'Statistics'
msgRoot['From'] = strFrom
msgRoot['To'] = strTo
msgRoot.preamble = 'This is a multi-part message in MIME format.'

msgAlternative = MIMEMultipart('alternative')
msgRoot.attach(msgAlternative)

msgText = MIMEText('This is the alternative plain text message.')
msgAlternative.attach(msgText)

msgText = MIMEText('<b>Number of reports: </b>'+ str(df['COUNT'][0])
                   '<br><img src="cid:image1" table align="left">'
                   '<br><img src="cid:image2" table align="center"><br>','html')

msgAlternative.attach(msgText)

fp = open('plot1.png', 'rb')
msgImage1 = MIMEImage(fp.read())
fp.close()
msgImage1.add_header('Content-ID', '<image1>')
msgRoot.attach(msgImage1)

fp = open('plot.png', 'rb')
msgImage2 = MIMEImage(fp.read())
fp.close()
msgImage2.add_header('Content-ID', '<image2>')
msgRoot.attach(msgImage2)

import smtplib
smtpServer='***'
server = smtplib.SMTP(smtpServer)
server.sendmail(strFrom, strTo, msgRoot.as_string())
server.quit()
Ana
  • 325
  • 2
  • 11

1 Answers1

0

I have used this:

https://wkhtmltopdf.org/

rock solid for me in many applications over the years. Probably have done 100's of thousands of them over the years, and never had an issue.

Convert your email body with images, into html, write it out to disk, and then shell out to the wkhtmltopdf executable to generate the PDF from the gnerated html.

wkhtmltopdf and wkhtmltoimage are open source (LGPLv3) command line tools to render HTML into PDF and various image formats using the Qt WebKit rendering engine. These run entirely "headless" and do not require a display or display service.

E.J. Brennan
  • 45,870
  • 7
  • 88
  • 116