Python: "subject" not shown when sending email using smtplib module

nsh picture nsh · Aug 29, 2011 · Viewed 92.4k times · Source

I am successfully able to send email using the smtplib module. But when the emial is sent, it does not include the subject in the email sent.

import smtplib

SERVER = <localhost>

FROM = <from-address>
TO = [<to-addres>]

SUBJECT = "Hello!"

message = "Test"

TEXT = "This message was sent with Python's smtplib."
server = smtplib.SMTP(SERVER)
server.sendmail(FROM, TO, message)
server.quit()

How should I write "server.sendmail" to include the SUBJECT as well in the email sent.

If I use, server.sendmail(FROM, TO, message, SUBJECT), it gives error about "smtplib.SMTPSenderRefused"

Answer

Roman Bodnarchuk picture Roman Bodnarchuk · Aug 29, 2011

Attach it as a header:

message = 'Subject: {}\n\n{}'.format(SUBJECT, TEXT)

and then:

server = smtplib.SMTP(SERVER)
server.sendmail(FROM, TO, message)
server.quit()

Also consider using standard Python module email - it will help you a lot while composing emails.