Friday, October 17, 2014

Sending email from a gmail account using python

In this guide I'll walk you through the python commands that you can use to send an email to someone from your gmail account. If you don't have python set it up in your environment look here for detail. Enter the commands step by step.
[shazni@shazniInWSO2 bin]$ python
Python 2.7.5 (default, Jun 25 2014, 10:19:55)
[GCC 4.8.2 20131212 (Red Hat 4.8.2-7)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> fromAddress="aaaaaaaaaaaa@gmail.com"
>>> toAddress="bbbbbbbbbbbb@yahoo.com"
>>> msg="Subject: Hello\n\nHi!! How are you"
>>> import smtplib
>>> server=smtplib.SMTP("smtp.gmail.com", 587)
>>> server.starttls()
(220, '2.0.0 Ready to start TLS')
>>> password="xxxxxxxxxxxxxx"
>>> server.login(fromAddress, password)
(235, '2.7.0 Accepted')
>>> server.sendmail(fromAddress, toAddress, msg)
{}
Replace 'aaaaaaaaaaaa', 'bbbbbbbbbbbb' and 'xxxxxxxxxxxxxx' accordingly.

You can easily put this into a python script and invoke it and send a quick email to someone from the command line without ever opening your email account in a browser. Following is a sample script which does the same as above.
#!/usr/bin/python

import smtplib
import getpass

fromAddress = raw_input("Enter your gmail address: ")
toAddress = raw_input("Enter the recipients email address: ")
subject = raw_input('Enter the subject of email: ')
bodyText = raw_input('Enter the body text: ')

msg = "Subject: " + subject + "\n\n" + bodyText

#msg="Subject: Hello\n\nHi!! How are you"

server=smtplib.SMTP("smtp.gmail.com", 587)
server.starttls()

password = getpass.getpass('Gmail Password: ')
server.login(fromAddress, password)
server.sendmail(fromAddress, toAddress, msg)
A sample run of the script is shown below.
[shazni@shazniInWSO2 Python]$ python sendEmail.py
Enter your gmail address: mshazninazeer@gmail.com
Enter the recipients email address: mshazninazeer@yahoo.com   
Enter the subject of email: Hello
Enter the body text: This is a sample text sent to you by python!!!
Gmail Password:
[shazni@shazniInWSO2 Python]$
Enjoy using python script to send emails

2 comments:

  1. Traceback (most recent call last):
    File "./email.test.py", line 19, in
    server.login(fromAddress, password)
    File "/usr/lib/python2.7/smtplib.py", line 615, in login
    raise SMTPAuthenticationError(code, resp)
    smtplib.SMTPAuthenticationError: (534, '5.7.14 Please log in via your web browser and\n5.7.14 then try again.\n5.7.14 Learn more at\n5.7.14 https://support.google.com/mail/bin/answer.py?answer=78754 141sm4582829ioz.39 - gsmtp')

    ReplyDelete
  2. I tried this using python2.7 and it works for me. This will only work for a gmail account. Also this may not work for an account where 2-step verification is enabled. Make sure you enter the passowrd correctly.

    ReplyDelete