Specify a sender when sending mail with Python (smtplib)

smtplib doesn't automatically include a From: header, so you have to put one in yourself:

message = 'From: [email protected]\nSubject: [PGS]: Results\n\nBlaBlaBla'

(In fact, smtplib doesn't include any headers automatically, but just sends the text that you give it as a raw message)


You can utilize the email.message.Message class, and use it to generate mime headers, including from:, to: and subject. Send the as_string() result via SMTP.

>>> from email import message
>>> m1=message.Message()
>>> m1.add_header('from','[email protected]')
>>> m1.add_header('to','[email protected]')
>>> m1.add_header('subject','test')
>>> m1.set_payload('test\n')
>>> m1.as_string()
'from: [email protected]\nto: [email protected]\nsubject: test\n\ntest\n'
>>> 

See this answer, it's working for me.

example code:

#send html email
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.header import Header
from email.utils import formataddr

msg = MIMEMultipart('alternative')
msg['From'] = formataddr((str(Header('MyWebsite', 'utf-8')), '[email protected]'))
msg['To'] = '[email protected]'

html = "email contents"

# Record the MIME types of text/html.
msg.attach(MIMEText(html, 'html'))

# Send the message via local SMTP server.
s = smtplib.SMTP('localhost')

# sendmail function takes 3 arguments: sender's address, recipient's address
# and message to send - here it is sent as one string.
s.sendmail('[email protected]', '[email protected]', msg.as_string())
s.quit()