[Tutor] question about headers and smtplib

Justin Ezequiel justin.mailinglists at gmail.com
Tue Aug 1 05:03:12 CEST 2006

When I first started with Python, I used MimeWriter to create E-mails.

Then some mail servers rejected my E-mails.

Some research (google) indicated (to me) that I needed a MIME-Version header.
(Can't recall now if I also needed a Content-Type header.)

Anyway, more research (Python docs) indicated that I should use the
email package instead.
I have been doing so since and have not had reports of anymore rejected E-mails.

Hope this helps.

>>> import email
>>> from email.MIMENonMultipart import MIMENonMultipart
>>> from email.Utils import formataddr
>>> format_addresses = lambda pairs: ', '.join([formataddr(pair) for
pair in pairs])
>>> msg = MIMENonMultipart('text', 'plain', charset='us-ascii')
>>> msg.set_payload('Foo Bar')
>>> msg.add_header('From', formataddr(('Justin', 'a at b.com')))
>>> msg.add_header('To', format_addresses([('Justin', 'a at b.com'),
('You', 'c at e.com')]))
>>> print msg.as_string()
Content-Type: text/plain; charset="us-ascii"
MIME-Version: 1.0
From: Justin <a at b.com>
To: Justin <a at b.com>, You <c at e.com>

Foo Bar

More information about the Tutor mailing list