Add Subject header to server.sendmail() in Python
12,880
Solution 1
You need to put the subject
in the header of the message.
Example -
import smtplib
msg = """From: [email protected]
To: [email protected]\n
Subject: <Subject goes here>\n
Here's my message!\nIt is lovely!
"""
server = smtplib.SMTP_SSL('smtp.example.com', port=465)
server.set_debuglevel(1)
server.ehlo
server.login('examplelogin', 'examplepassword')
server.sendmail('[email protected]', ['[email protected] '], msg)
server.quit()
Solution 2
You can simply use MIMEMultipart()
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
msg = MIMEMultipart()
msg['From'] = 'EMAIL_USER'
msg['To'] = 'EMAIL_TO_SEND'
msg['Subject'] = 'SUBJECT'
body = 'YOUR TEXT'
msg.attach(MIMEText(body,'plain'))
text = msg.as_string()
server = smtplib.SMTP('smtp.gmail.com',587)
server.starttls()
server.login('email','password')
server.sendmail(email_user,email_send,text)
server.quit()
Hope this works!!!
Solution 3
import smtp
def send_email(SENDER_EMAIL,PASSWORD,RECEIVER_MAIL,SUBJECT,MESSAGE):
try:
server = smtplib.SMTP("smtp.gmail.com",587)
#specify server and port as per your requirement
server.starttls()
server.login(SENDER_EMAIL,PASSWORD)
message = """From: %s\nTo: %s\nSubject: %s\n\n%s""" % (SENDER_EMAIL, ", ".join(TO), SUBJECT, MESSAGE)
server.sendmail(SENDER_EMAIL,TO,message)
server.quit()
print 'successfully sent the mail'
except:
print "failed to send mail"
send_email("[email protected]","Password","[email protected]","SUBJECT","MESSAGE")
Author by
user248884
Updated on June 04, 2022Comments
-
user248884 almost 2 years
I'm writing a python script to send emails from the terminal. In the mail which I currently send, it is without a subject. How do we add a subject to this email?
My current code:
import smtplib msg = """From: [email protected] To: [email protected]\n Here's my message!\nIt is lovely! """ server = smtplib.SMTP_SSL('smtp.example.com', port=465) server.set_debuglevel(1) server.ehlo server.login('examplelogin', 'examplepassword') server.sendmail('[email protected]', ['[email protected] '], msg) server.quit()