smtplib sends blank message if the message contain certain characters

Viewed 9869

My current script allows me to send emails fine, but there are just some characters it doesn't like, particularly ':' in this sample.

import smtplib, sys

mensaje = sys.argv[1]
def mailto(toaddrs, msg):
    fromaddr = 'myemailblabla'

    username = 'thisismyemail'
    password = '122344'

    server = smtplib.SMTP('smtp.gmail.com:587')
    server.starttls()
    server.login(username, password)
    server.sendmail(fromaddr, toaddrs, msg)
    server.quit()

mailto('test@gmail.com', mensaje)

If I write a sample message such as, let's say "Hi there\n how are you?" it works fine, but let's say I try to send a url http://www.neopets.com, the email is sent blank. I believe the ':' causes this issue, so I tried escaping it, but nothing.

3 Answers

The proper solution is to use the Python email library to create a valid message, instead of painstakingly learning (or wildly guessing at random) how to construct a valid MIME message structure by joining together pieces of text.

A trivial RFC822 message which contains only ASCII can easily be created with

"From: {0}\nTo: {1}\nSubject: {2}\n\n{3}".format(
    fromaddr, toaddr,
    "Hello, I am the exiled prince of Ubandingba",
    "http://clickme.example.net/scam/")

but as soon as you need anything with other character sets, lines longer than some 80 characters, content types other than plain text, or in general anything more advanced than plain text English-language email as it was in 1990, the code should look something like

from email.message import EmailMessage

msg = EmailMessage()
msg["from"] = fromaddr
msg["to"] = toaddr
msg["subject"] = "You have been nominated for the Nobel prize"
msg.set_content("http://scam.example.org/clickme")

which is admittedly slightly more verbose, but also infinitely more versatile, robust, and extensible.

This uses the EmailMessage API which was officially introduced in Python 3.6. New code should probably target this platform rather than the legacy email.Message module from earlier versions, although most online code examples you can find will be for the older Python library. See the Python email examples documentation for some quick examples.

Related