aeduG aeduG - 1 year ago 75
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'

The problem is, when I print the message,


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 Source

Try this


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())

send_email("", ",")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download