Problems with headers in email.message

Carsten Haese carsten at uniqsys.com
Sat Aug 4 12:14:35 EDT 2007


On Sat, 2007-08-04 at 15:38 +0000, Slippy wrote:
> [...]
> import smtplib, email
> from email.message import Message
> m = Message( )
> m['From'] = 'Slippy <user at myemail.com>'
> m['To'] = 'mygroup at googlegroups.com'
> m['Subject'] = 'A Test Message'
> m.set_payload('This is a test email. Please ignore')
> s = smtplib.SMTP('smtp.myemail.com')
> failed =
> s.sendmail('user at myemail.com','mygroup at googlegroups.com',str(m))
> if failed:
>  print 'Message sending failed.'
> else:
>  print 'Message sent.'
> print 'Bye.'
> -------------Snip Here-------------Snip Here-------------Snip
> Here-------------
> 
> Now, I get all the right responses, and the message sends ok. I go and
> check my inbox, and the message is there, but the From, To and Subject
> lines I created (as well as a preceding blank line and a "From nobody"
> line) are in the message body, followed by the body text.
> 
> How do I assign values to the header?

The way you're doing it is fine as far as assigning headers goes. My
semi-educated guess is that either your mail-transfer agent or Google
Groups' MTA is being confused by the "Unix From" envelope (that's the
"From nobody..." you're seeing) that is included by str(m).

Try m.as_string() instead, which doesn't include the Unix From envelope.

I'd also like to point out that email.message is overkill for your
simple use case. An email message is simply a series of headers followed
by a blank line followed by the message body, which you can easily build
manually if the headers aren't too long and the body is plain text:

email_message = """\
From: %s
To: %s
Subject: %s

%s""" % (email_from, email_to, email_subject, email_body)

HTH,

-- 
Carsten Haese
http://informixdb.sourceforge.net





More information about the Python-list mailing list