Search code examples
pythonemailsmtpsmtplib

Python emailing pdf getting unexpected keyword argument 'main_type'


I am trying to attach a pdf and send an email in python. Getting below error-

TypeError: set_bytes_content() got an unexpected keyword argument 'main_type'.

Newbie here, dont know what i am doing wrong?

import os
import smtplib
from email.message import EmailMessage
import PyPDF2


EMAIL_ADDRESS = os.environ.get('EMAIL_USER')
EMAIL_PASSWORD = os.environ.get('EMAIL_PASS')

msg = EmailMessage()
msg['Subject'] = 'EDs Diet Plan'
msg['From'] = EMAIL_ADDRESS
msg['To'] = 'test@gmail.com'  
msg.set_content('Please find attached your customized diet plan and the general list of foods')

file = 'LFV Diet.pdf'

with open(file, 'rb') as f:
    file_data = f.read()
    #file_type =
    file_name = f.name

msg.add_attachment(file_data, main_type='application', subtype='octet-stream', file_name=file_name)

with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:
    smtp.login(EMAIL_ADDRESS, EMAIL_PASSWORD)
    smtp.send_message(msg)


Solution

  • You have some typos - just change main_type to maintype and file_name to filename.

    BEFORE:

    msg.add_attachment(file_data, main_type='application', subtype='octet-stream', file_name=file_name)
    

    AFTER:

    msg.add_attachment(file_data, maintype='application', subtype='octet-stream', filename=file_name)
    

    Some good examples are here - https://docs.python.org/3/library/email.examples.html