Search code examples
pythonemail-attachments

Send E-mail with Attachment which is a pdf


Trying to send a e-mail with a PDF attachment. I am able to send the e-mail but it will only attach the pdf file. There is no body sent with the e-mail.

import smtplib
from email.mime.text import MIMEText

from email.message import EmailMessage
#from email import encoders

email_user = 'my.email@email.com'
email_send = input('Enter address to Send e-mail to: ')
subject = 'Python!'

msg = EmailMessage()
msg['From'] = email_user
msg['To'] = email_send
msg['Subject'] = subject

body = 'Hi there, This is a test E-mail from Python!' #This part is missing
msg.attach(MIMEText(body, 'plain')) 


filename = 'my_file'


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

text = msg.as_string()






server = smtplib.SMTP('server',port)
server.sendmail(email_user, email_send, text)
server.quit

Solution

  • Instead of

       msg.attach(MIMEText(body, 'plain')) 
    

    try below

     msg.set_content(body)