Send email from gmail with Python

Hey,

today’s assignment is to send a text email to an arbitrary recipient by using an existing gmail account. We will send the email by using the blog’s favorite scripting language, Python. For you who wonder if we could attach an image or an arbitrary file to an email & send it with the main content, yes, we can, but in this article i would like to focus simply on text emails, without attachments.

Requirements

  • An existing gmail account
  • Python’s S(imple)M(ail)T(ransfer)P(rotocol)lib module. smtplib is already installed with Python, thus you don’t need to “pip search” & “pip install” it.

How

With the following script, we can send an email to any number of recipients (“tom@gmail.com”) through our existing gmail account (“kaze@gmail.com”). We need to build our email by filling the email content string (the variable message), then logon to the gmail server through the server’s smtp daemon, send the message & finally close connection with the smtp daemon of the gmail server. We use the smtp protocol because in the gmail case, gmail’s servers (to which we need to login in order to send the email) have attached & running an smpt daemon-service, allowing them to “listen” to smtp email requests.

def send_email(user, pwd, recipient, subject, body):
   import smtplib
     gmail_user = user
     gmail_pwd = pwd
     FROM = user
     TO = recipient if type(recipient) is list else [recipient]
     SUBJECT = subject
     TEXT = body     # Prepare actual message
     message = “”“\From:%sTo:%s\nContent-type:text/html\n
                 MIME-Version:1.0\n
                 Subject:%s\n\n%s”“” % (FROM, “, “.join(TO), SUBJECT, TEXT)
     #print message
    try:
         server = smtplib.SMTP_SSL(“smtp.gmail.com”)
         server.login(gmail_user, gmail_pwd)
         server.sendmail(FROM, TO, message)
         server.close()
         #print ‘successfully sent the mail’
        return True
     except Exception as e:
         print repr(e)
           #print “failed to send mail”
         return Falseif __name__ == ‘__main__’:
    send_email(‘kaze@gmail.com’,
    ‘TzertzelosCrew.666.’,
    [‘tom@gmail.com’],
    ‘Not a spam!’,
    ‘You listen,i code!’)

 

Gmail Login Failure

In case the login() call fails with the following error

Please log in via your web browser and then try again

visit: https://www.google.com/settings/security/lesssecureapps

The page says: “Some apps and devices use less secure sign-in technology, which makes your account more vulnerable. You can turn off access for these apps, which we recommend, or turn on access if you want to use them despite the risks”

and click on “Turn On” (if you want Google to allow you to send the email through your app/script).

At the moment, i have no clue how to send an email without turning that account feature to “Off“. Consider this as an assignment for yourself 🙂

Why wanting to send emails?

Because you would like to get notified by one of your programs in case of

  • an abnormal behavior,
  • a task completion,
  • a data change,

in general, in case specific conditions have been met inside your code & something interesting just happened, while you are away from the console that executes your precious script. By using smtplib through the previous function, you could just fill the subject & content depending the occasion inside your code.

Now, go & spam yourselves.

kazeone

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s