Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

smtplib sends blank message if the message contain certain characters

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('[email protected]', 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.

like image 523
Stupid.Fat.Cat Avatar asked Aug 03 '12 13:08

Stupid.Fat.Cat


1 Answers

The problem is that smtplib is not putting a blank line between the message header and the message body as shown by in the "Show Original" form of my test:

Return-Path: <[email protected]>
Received: **REDACTED**
        Fri, 03 Aug 2012 06:56:20 -0700 (PDT)
Message-ID: <[email protected]>
Date: Fri, 03 Aug 2012 06:56:20 -0700 (PDT)
From: [email protected]
http: //www.example.com

Although this is a legal mail header, Mail Transfer Agents and Mail User Agents should ignore apparent header fields they don't understand. And because the RFC822 header continues until the first blank line and http: looks like a header line, it is parsed as if it were a header. If given a newline:

mensaje = '\nhttp://www.example.com'

Then it works as expected. Although email technically only needs the "envelope" as provided by smtplib the contents of the mail should be more complete if you expect your recipients (and their mailers) to treat the message nicely, you should probably use the email module to generate the body.

added

Based on the doctest in smtplib.py it looks as if this is an intentional feature allowing the caller of sendmail() to append to the header:

     >>> msg = '''\\
     ... From: [email protected]
     ... Subject: testin'...
     ...
     ... This is a test '''
     >>> s.sendmail("[email protected]", tolist, msg)

Where the From: and Subject: lines are part of the "nice" headers I mentioned above.

like image 90
msw Avatar answered Nov 13 '22 16:11

msw