3

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()
user248884
  • 851
  • 1
  • 11
  • 21

4 Answers4

7

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()
Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176
5

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!!!

skaul05
  • 2,154
  • 3
  • 16
  • 26
1
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")
H S Umer farooq
  • 981
  • 1
  • 8
  • 14
0

Indeed, the subject you missed. Those things can easily be avoided by using some API (such as yagmail) rather than the headers style.

I believe yagmail (disclaimer: I'm the maintainer) can be of great help to you, since it provides an easy API.

import yagmail
yag = yagmail.SMTP('[email protected]', 'yourpassword')
yag.send(to = '[email protected]', subject ='Your subject', contents = 'Some message text')

That's only three lines indeed.

Install with pip install yagmail or pip3 install yagmail for Python 3.

More info at github.

PascalVKooten
  • 20,643
  • 17
  • 103
  • 160