Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

smtplib

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"

like image 507
nsh Avatar asked Aug 29 '11 15:08

nsh


People also ask

What is Smtplib in Python How can you use Python built-in mail server explain?

The smtplib module The smtplib is a Python library for sending emails using the Simple Mail Transfer Protocol (SMTP). The smtplib is a built-in module; we do not need to install it. It abstracts away all the complexities of SMTP.


2 Answers

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.

like image 162
Roman Bodnarchuk Avatar answered Sep 21 '22 10:09

Roman Bodnarchuk


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() 
like image 37
emehex Avatar answered Sep 24 '22 10:09

emehex