aeduG aeduG - 1 month ago 7
Python Question

Create simple plain text Email in Python

I am trying to create a simple email message that I would like to send to an smtp-server.

Here is what I do:

from email.message import EmailMessage()
message = 'blabla'
email = EmailMessage()
email['Subject'] = 'bla'
email['From'] = 'someone'
email['To'] = 'someone else'
email.set_payload(message)


The problem is, when I print the message,

print(email.as_string())
print(email.get_payload())


the output does not contain the original message (blabla).
It prints the header data, and an empty string below that!
Why is that?

I would like to receive a message on the smtp-server, parse it and separate the message and the headers as it is done in this post:

How can I get an email message's text content using python?

But if the message is not even in the email, I can't do that.
Can somebody tell me what I do wrong?

Answer

Try this

#!/usr/bin/python3

import smtplib
import email.message
import email.utils


def send_email(send_from, send_to):

    msg = email.message.Message()
    msg['From'] = send_from
    msg['To'] = send_to
    msg['Subject'] = "E-mail Subject"
    msg.add_header('Content-Type', 'text')
    msg.set_payload("This is your message.")

    smtp_obj = smtplib.SMTP("localhost")
    smtp_obj.sendmail(msg['From'], [msg['To']], msg.as_string())
    smtp_obj.quit()

send_email("your@email.com", "to@email.com,")