Kesi Kesi - 4 months ago 12
Python Question

Python Smptlib Email (Wrong subject & message field)

Everytime I send an email with this function, it doesn't add the subject and the message to the right fields, but instead of that, it adds it to the 'from:' or something.
Here's the image of it.
Any idea how this can be fixed? Thanks for answer

import smtplib

## NON-ANONYMOUS EMAIL
def email():
# Parts of an email
SERVER = 'smtp.gmail.com'
PORT = 587
USER = 'something@gmail.com'
PASS = 'something'
FROM = USER
TO = ['something@riseup.net']
#SUBJECT = 'Test'
MESSAGE = 'Test message.'

# Connects all parts of email together
message = "From: %s\r\n To: %s\r\n %s" % (FROM, ", ".join(TO), MESSAGE)

# Sends an email
email = smtplib.SMTP()
email.connect(SERVER,PORT)
email.starttls()
email.login(USER,PASS)
email.sendmail(FROM, TO, message)
email.quit()

email()

Answer

Following on from @tripleee suggestion to use the email module, here's a basic example using your current code:

import smtplib
from email.mime.text import MIMEText

## NON-ANONYMOUS EMAIL
def email():
    # Parts of an email
    SERVER = 'smtp.gmail.com'
    PORT = 587
    USER = 'something@gmail.com'
    PASS = 'something'
    FROM = USER
    TO = ['something@riseup.net']
    SUBJECT = 'Test'

    # Create the email
    message = MIMEText('Test message.')
    message['From'] = FROM
    message['To'] = TO
    message['Subject'] = SUBJECT

    # Sends an email
    email = smtplib.SMTP()
    email.connect(SERVER,PORT)
    email.starttls()
    email.login(USER,PASS)
    email.sendmail(FROM, TO, message.as_string())
    email.quit()

Notice how much easier it is to define the parts of the email using keys like message['Subject'] instead of attempting to build a string or 'gluing parts together' as tripleee put it.

The different fields (From, To, Subject, et cetera) you can access are defined in RFC 2822 - Internet Message Format.

These documents are not easy to read, so here's a list of some of the fields' keys you can use: To, From, Cc, Bcc, Reply-To, Sender, Subject.

You cannot have a space after the \r\n. An email header line is continued by indenting it, so your code is creating a really long From: header with all the data you are trying to put in different fields.

As triplee and the RFC-2822 document says, if you are wanting to build the email string manually look at the field definitions in that document which look similar to this example:

from = "From:" mailbox-list CRLF

You can translate this into Python code when building an email string like so:

"From: something@riseup.net \r\n"

Comments