Alex Rivera | Logout

Specify a sender when sending mail with Python (smtplib)

Asked 2009-02-12T11:52:40.637
15

I have a very simple piece of code (just for testing):

import smtplib
import time

server = 'smtp.myprovider.com'
recipients = ['johndoe@somedomain.com']
sender = 'me@mydomain.com'
message = 'Subject: [PGS]: Results\n\nBlaBlaBla'

session = smtplib.SMTP(server)

session.sendmail(sender,recipients,message);

This works but the problem is that e-mail clients don't display a sender. I want to be able to add a sender name to the e-mail. Suggestions?

Edit
Report

1 Answer

12

The "sender" you're specifying in this case is the envelope sender that is passed onto the SMTP server.

What your MUA (Mail User Agent - i.e. outlook/Thunderbird etc.) shows you is the "From:" header.

Normally, if I'm using smtplib, I'd compile the headers separately:

headers = "From: %s\nTo: %s\n\n" % (email_from, email_to)

The format of the From header is by convention normally "Name" <user@domain>

You should be including a "Message-Id" header and a "Reply-To" header as well in all communications. Especially since spam filters may pick up on the lack of these as a great probability that the mail is spam.

If you've got your mail body in the variable body, just compile the overall message with:

message = headers + body

Note the double newline at the end of the headers. It's also worth noting that SMTP servers should separate headers with newlines only (i.e. LF - linfeed). However, I have seen a Windows SMTP server or two that uses \r\n (i.e. CRLF). If you're on Windows, YMMV.

answered 2009-02-12T12:22:54.420

Your Answer