Search code examples
pythonsmtplib

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


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

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"


Solution

  • 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. Using it would look like this:

    from email.message import EmailMessage
    
    msg = EmailMessage()
    msg['Subject'] = SUBJECT
    msg['From'] = FROM
    msg['To'] = TO
    msg.set_content(TEXT)
    
    server.send_message(msg)