ThatOnePythonNoob ThatOnePythonNoob - 2 months ago 7
Python Question

How to add a subject to an email being sent with gmail?

I am trying to send an email using GMAIL with a subject and a message. I have succeeded in sending an email using GMAIL without the implementation of

subject
and have also been able to receieve the email. However whenever I try to add a subject the program simply does not work.

import smtplib
fromx = 'email@gmail.com'
to = 'email1@gmail.com'
subject = 'subject' #Line that causes trouble
msg = 'example'
server = smtplib.SMTP('smtp.gmail.com:587')
server.starttls()
server.ehlo()
server.login('email@gmail.com', 'password')
server.sendmail(fromx, to, subject , msg) #'subject'Causes trouble
server.quit()


error line:

server.sendmail(fromx, to, subject , msg) #'subject'Causes trouble

Answer

The call to smtplib.SMTP.sendmail() does not take a subject parameter. See the doc for instructions on how to call it.

Subject lines, along with all other headers, are included as part of the message in a format called RFC822 format, after the now-obsolete document that originally defined the format. Make your message conform to that format, like so:

import smtplib
fromx = 'xxx@gmail.com'
to  = 'xxx@gmail.com'
subject = 'subject' #Line that causes trouble
msg = 'Subject:{}\n\nexample'.format(subject)
server = smtplib.SMTP('smtp.gmail.com:587')
server.starttls()
server.ehlo()
server.login('xxx@gmail.com', 'xxx')
server.sendmail(fromx, to, msg)
server.quit()

Of course, the easier way to conform your message to all appropriate standards is to use the Python email.message standard library, like so:

import smtplib
from email.mime.text import MIMEText

fromx = 'xxx@gmail.com'
to  = 'xxx@gmail.com'
msg = MIMEText('example')
msg['Subject'] = 'subject'
msg['From'] = fromx
msg['To'] = to

server = smtplib.SMTP('smtp.gmail.com:587')
server.starttls()
server.ehlo()
server.login('xxx@gmail.com', 'xxx')
server.sendmail(fromx, to, msg.as_string())
server.quit()

Other examples are also available.