How to add a subject to an email being sent with gmail?
<p>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 <code>subject</code> and have also been able to receieve the email. However whenever I try to add a subject the program simply does not work.</p>

<pre><code>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()
</code></pre>

<p>error line:</p>

<pre><code>server.sendmail(fromx, to, subject , msg) #'subject'Causes trouble
</code></pre>

<p>The call to <code>smtplib.SMTP.sendmail()</code> does not take a <code>subject</code> parameter. See <a href="https://docs.python.org/2/library/smtplib.html#smtplib.SMTP.sendmail" rel="nofollow">the doc</a> for instructions on how to call it.</p>

<p>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:</p>

<pre><code>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()
</code></pre>

<p>Of course, the easier way to conform your message to all appropriate standards is to use the Python <a href="https://docs.python.org/2/library/email.message.html" rel="nofollow"><code>email.message</code></a> standard library, like so:</p>

<pre><code>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()
</code></pre>

<p><a href="https://docs.python.org/2/library/email-examples.html#email-examples" rel="nofollow">Other examples</a> are also available. </p>

python python-2.7 email gmail subject