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

PythonSmtplib

Python Problem Overview


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"

Python Solutions


Solution 1 - Python

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.

Solution 2 - Python

This will work with Gmail and Python 3.6+ using the new "EmailMessage" object:

import smtplib
from email.message import EmailMessage

msg = EmailMessage()
msg.set_content('This is my message')

msg['Subject'] = 'Subject'
msg['From'] = "[email protected]"
msg['To'] = "[email protected]"

# Send the message via our own SMTP server.
server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
server.login("[email protected]", "password")
server.send_message(msg)
server.quit()

Solution 3 - Python

try this:

import smtplib
from email.mime.multipart import MIMEMultipart
msg = MIMEMultipart()
msg['From'] = 'sender_address'
msg['To'] = 'reciver_address'
msg['Subject'] = 'your_subject'
server = smtplib.SMTP('localhost')
server.sendmail('from_addr','to_addr',msg.as_string())

Solution 4 - Python

You should probably modify your code to something like this:

from smtplib import SMTP as smtp
from email.mime.text import MIMEText as text

s = smtp(server)

s.login(<mail-user>, <mail-pass>)

m = text(message)

m['Subject'] = 'Hello!'
m['From'] = <from-address>
m['To'] = <to-address>

s.sendmail(<from-address>, <to-address>, m.as_string())

Obviously, the <> variables need to be actual string values, or valid variables, I just filled them in as place holders. This works for me when sending messages with subjects.

Solution 5 - Python

See the note at the bottom of smtplib's documentation:

In general, you will want to use the email package’s features to construct an email message, which you can then convert to a string and send via sendmail(); see email: Examples.

Here's the link to the examples section of email's documentation, which indeed shows the creation of a message with a subject line. https://docs.python.org/3/library/email.examples.html

It appears that smtplib doesn't support subject addition directly and expects the msg to already be formatted with a subject, etc. That's where the email module comes in.

Solution 6 - Python

I think you have to include it in the message:

import smtplib

message = """From: From Person <[email protected]>
To: To Person <[email protected]>
MIME-Version: 1.0
Content-type: text/html
Subject: SMTP HTML e-mail test

This is an e-mail message to be sent in HTML format

<b>This is HTML message.</b>
<h1>This is headline.</h1>
"""

try:
   smtpObj = smtplib.SMTP('localhost')
   smtpObj.sendmail(sender, receivers, message)         
   print "Successfully sent email"
except SMTPException:
   print "Error: unable to send email"

code from: http://www.tutorialspoint.com/python/python_sending_email.htm

Solution 7 - Python

import smtplib
 
# creates SMTP session 

List item

s = smtplib.SMTP('smtp.gmail.com', 587)
 
# start TLS for security   
s.starttls()
 
# Authentication  
s.login("login mail ID", "password")
 
 
# message to be sent   
SUBJECT = "Subject"   
TEXT = "Message body"
 
message = 'Subject: {}\n\n{}'.format(SUBJECT, TEXT)
 
# sending the mail    
s.sendmail("from", "to", message)
 
# terminating the session    
s.quit()

Solution 8 - Python

In case of wrapping it in a function, this should work as a template.

def send_email(login, password, destinations, subject, message):
    server = smtplib.SMTP_SSL("smtp.gmail.com", 465)

    server.login(login, password)
    message = 'Subject: {}\n\n{}'.format(subject, message)

    for destination in destinations:
        print("Sending email to:", destination)
        server.sendmail(login, destinations, message)

    server.quit()

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionnshView Question on Stackoverflow
Solution 1 - PythonRoman BodnarchukView Answer on Stackoverflow
Solution 2 - PythonemehexView Answer on Stackoverflow
Solution 3 - PythonHackaholicView Answer on Stackoverflow
Solution 4 - Pythong.d.d.cView Answer on Stackoverflow
Solution 5 - Pythonjeffcook2150View Answer on Stackoverflow
Solution 6 - PythonMartinView Answer on Stackoverflow
Solution 7 - PythonKing_AviView Answer on Stackoverflow
Solution 8 - PythonMatheus GoulartView Answer on Stackoverflow