1
mail.login(email_username, email_password)
mail.select('Inbox')
result, data = mail.search(None, '(FROM "abc@gmail.com" SUBJECT "Hello")' )
ids = data[0]

After searching for a particular mail from mail inbox, I want to download the mail as pdf. I've looked elsewhere, but I could only find parsing mail content using get_payload() method. Is there any module in python to save the mail as we manually do by clicking on print button in gmail? Thanks all.

Sreelal
  • 11
  • 2

2 Answers2

1

Most email is HTML, so chucking in any HTML-to-PDF converter from this question works.

I also swapped out imaplib for imap_tools for you because it has an easier API:

import pdfkit
from imap_tools import MailBox

with MailBox('imap.gmail.com').login(email_username, email_password, 'INBOX') as mailbox:
    for i, msg in enumerate(mailbox.fetch('ALL', limit=10)):
        html = '<meta http-equiv="Content-type" content="text/html; charset=utf-8"/>' + \
               msg.html
        pdfkit.from_string(html, str(i) + '.pdf')

Notes:

  • pdfkit does not handle non-ASCII unless you add a utf-8 header like I did
  • Some messages might not have HTML content, use msg.html or msg.text for them
  • I installed Chocolatey, then used choco to install wkhtmltopdf (pdfkit dependency)
  • I am using GMail, which requires turning on less secure apps here (SO)

Results (this is from 2012):

enter image description here

xjcl
  • 12,848
  • 6
  • 67
  • 89
0

You could try using ReportLab to create a pdf file with the content you get from the get_payload() method

naderabdalghani
  • 1,139
  • 2
  • 14
  • 21