Python mail inserts spaces every 171 characters

I am trying to write a python script to send an email using html formatting and includes many inextricable spaces. However, when I run it, some of the & nbsp lines are interrupted by spaces that occur every 171 characters, as can be seen from this example:

#!/usr/bin/env python import smtplib import socket from email.mime.text import MIMEText emails = [" my@email.com "] sender = " test@ {0}".format(socket.gethostname()) message = "<html><head></head><body>" for i in range(20): message += "&nbsp;" * 50 message += "<br/>" message += "</body>" message = MIMEText(message, "html") message["Subject"] = "Test" message["From"] = sender message["To"] = ", ".join(emails) mailer = smtplib.SMTP("localhost") mailer.sendmail(sender, emails, message.as_string()) mailer.quit() 

In this example, there should be an empty email consisting of only spaces, but it looks something like this:

  &nbsp ; &nb sp; & nbsp; &nbs p; &n bsp; 

Edit: In case this is important, I am running Ubuntu 15.04 with Postfix for the smtp client and using python2.6.

+7
python email whitespace
source share
2 answers

I can reproduce this in some way, but my line breaks appear every 999 characters. RFC 821 says that the maximum line length is 1000 characters, including line breaks, so this is probably why.

This post provides another way to send a html email address in python, and I believe that the mime type "multipart / alternative" is the right way. Sending HTML Email Address Using Python

+5
source share

I'm a yagmail developer, a package that tries to make sending emails easier.

You can use the following code:

 import yagmail yag = yagmail.SMTP(' me@gmail.com ', 'mypassword') for i in range(20): message += "&nbsp;" * 50 message += "<br/>" yag.send(contents = message) 

Please note that by default it will send an HTML message and automatically add an alternative part for browsers without HTML.

Also note that when omitting subject an empty object will remain, and without the argument to it will send it to itself.

Also, note that if you configured yagmail correctly, you can simply log in using yag.SMTP() without having a username and password in the script (it’s still safe). If you pass the password, the message getpass .

Adding an attachment is as simple as pointing to a local file, for example:

 yag.send(contents = [message, 'previously a lot of whitespace', '/local/path/file.zip'] 

Amazing right? Thanks for letting me show you a good use case for yagmail :)

If you have any suggestions, problems or ideas, please let me know on github .

+2
source share

All Articles