Python mail puts unaccounted space in an Outlook subject line

I wrote a simple Python script that used MIMEMultipart and SMTPLib to send mail to the recipient array. The code looks something like this:

import smtplib import sys from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart sender=' foo@bar.com ' recipients=' someguy@bar.com ' subject='A pretty long subject line which looks like this' mail_server='microsfot_exchange_server_ip' msg = MIMEMultipart('alternative') body='Body of the Email' msg['Subject'] = subject msg['from'] = sender msg['to'] = ", ".join(recipients) s = smtplib.SMTP(mail_server) s.sendmail(sender, recipients, msg.as_string()) s.quit() 

This sends mail successfully, but the theme, like in Outlook Mail, looks something like this:

  A pretty long subject line which looks like this 
+5
source share
2 answers

It seems you got into Issue # 1974 :

Long email headers should be wrapped. This process is called "header folding" and is described in RFC822 . However, RFC822 seems to be a bit ambiguous about how header folding should be done.

Python in versions earlier than 2.7 / 3.1 happened in such a way that it called certain mail clients you wrote out (using the \t tab as a continuation character).

A workaround was suggested in the bug report: make your theme a header object as follows:

 from email.header import Header # ... msg['Subject'] = Header(subject) 

I just checked this and it really uses spaces instead of tabs as continuation characters that should solve your problem.

+6
source

Your subject line is longer than 78 characters and is split into .as_string() . The first few characters are in the subject line, and the remaining characters are on one or more continuation lines.

When Outlook restores the original subject line, it does it wrong.

You can try to avoid this by avoiding continuation lines, for example:

 from StringIO import StringIO from email.generator import Generator def my_as_string(msg): fp = StringIO() g = Generator(fp, mangle_from_=False, maxheaderlen=0) g.flatten(msg) return fp.getvalue() ... s.sendmail(sender, recipients, my_as_string(msg)) 

Literature:

+2
source

Source: https://habr.com/ru/post/1201842/


All Articles