1

I am trying to set up an automated email sending script. I am using the email module and the EmailMessage object from the email.message module and am sending the email using the smtplib module. I would like to be able to attach a .pdf file to an email but the documentation for the add_attachment() method for EmailMessage() is not very helpful and I'm not even sure I should be using it.

Here is what I have so far with irrelevant information removed:

import time
import smtplib
from email.message import EmailMessage

FROM = 'my email'

s = smtplib.SMTP('smtp.gmail.com', 587)
s.ehlo()
s.starttls()
s.login('my email', 'password')

for line in open('to.csv'):
    line = line.strip()
    fields = line.split(',')

    subject = 'subject'

    email = EmailMessage()

    email['Subject'] = 'subject'
    email['From'] = FROM
    email['To'] = 'to email'


    s.send_message(email)

    print('Sent to {0}'.format(fields[TO]))

    time.sleep(5)

s.quit()

How do I go about attaching the pdf file? I searched and saw one answer was using the MIMEText object to add attachments but it did not appear to work pdf.

martineau
  • 99,260
  • 22
  • 139
  • 249
  • Possible duplicate of https://stackoverflow.com/questions/3362600/how-to-send-email-attachments-with-python – ArturFH Jun 13 '17 at 19:53
  • Possible duplicate of [How to send email attachments with Python](https://stackoverflow.com/questions/3362600/how-to-send-email-attachments-with-python) – stovfl Jun 14 '17 at 18:47

1 Answers1

9

Late for the answer... but this is what I do:

email = EmailMessage()

email['Subject'] = 'subject'
email['From'] = FROM
email['To'] = 'to email'

with open('example.pdf', 'rb') as content_file:
    content = content_file.read()
    email.add_attachment(content, maintype='application', subtype='pdf', filename='example.pdf')

s.send_message(email)

By the way, this isnt a duplicate question, in this question, he use EmailMessage and don't use MIMEText / MIMEPart, etc.

Danila Vershinin
  • 6,133
  • 2
  • 20
  • 25
Gabriel
  • 691
  • 1
  • 10
  • 32
  • Short, succinct, and highly useable. This should be one of the examples included within the [standard python examples](https://docs.python.org/3/library/email.examples.html). – slightlynybbled Nov 26 '18 at 14:38
  • 2
    Surely `maintype` here should be `application`? – SColvin Mar 26 '19 at 16:01
  • @SColvin yes. I can confirm that `maintype='application/pdf'` results in `Content-Type: application/pdf/pdf`, although most clients won't care and do their own MIME sniffing by looking at `.pdf` in the filename of the attachment. Edited the answer. – Danila Vershinin Oct 23 '20 at 17:01