Skip to content Skip to sidebar Skip to footer

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 th

Solution 1:

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.

Anyway, manually gluing together snippets of plain text is a really crude and error-prone way to construct an email message. You will soon find that you need the various features of the Python email module anyway (legacy email is 7-bit single part ASCII only; you'll probably want one or more of attachments, content encoding, character set support, multipart messages, or one of the many other MIME features). This also coincidentally offers much better documentation for how to correcty create a trivial email message.

Solution 2:

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'] = ",".join(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"

Post a Comment for "Python Smptlib Email (wrong Subject & Message Field)"