Home > python > Send e-mails via Gmail

Send e-mails via Gmail

The following entry is based on the excellent post of Kutuma. Credits go to him.

I made some minor modifications: (1) conversion to module, (2) “From:” address shows the name too.

send_email_via_gmail.py module:

#!/usr/bin/env python

import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email import Encoders
import os

gmail_user = "username@gmail.com"
gmail_name = "User Name <username@gmail.com>"
gmail_pwd = "userpassword"

def mail(to, subject, text, attach):
   msg = MIMEMultipart()

   msg['From'] = gmail_name
   msg['To'] = to
   msg['Subject'] = subject

   msg.attach(MIMEText(text))

   part = MIMEBase('application', 'octet-stream')
   part.set_payload(open(attach, 'rb').read())
   Encoders.encode_base64(part)
   part.add_header('Content-Disposition',
           'attachment; filename="%s"' % os.path.basename(attach))
   msg.attach(part)

   mailServer = smtplib.SMTP("smtp.gmail.com", 587)
   #mailServer = smtplib.SMTP_SSL("smtp.gmail.com", 465)   # didn't work for me
   mailServer.ehlo()
   mailServer.starttls()
   mailServer.ehlo()
   mailServer.login(gmail_user, gmail_pwd)
   #mailServer.sendmail(gmail_user, to, msg.as_string())   # just e-mail address in the From: field
   mailServer.sendmail(gmail_name, to, msg.as_string())   # name + e-mail address in the From: field
   # Should be mailServer.quit(), but that crashes...
   mailServer.close()

if __name__ == "__main__":
    mail("send-mail-to-this-person@address.com",
       "Hello from Python!",
       "This is an e-mail sent with Python.",
       "/tmp/some-image.jpg")

How to use it in a script:

#!/usr/bin/env python

import send_email_via_gmail as gmail

gmail.mail( "send-mail-to-this-person@address.com",
                    "Subject of the mail",
                    "Body of the mail.",
                    "/tmp/report.pdf" )

Update (20130113): pushed on github.

Alternatives (20130810)
Recently I came across some alternatives that are easier to use:

  • envelopes
  • gmail (I tried it and it works well. I used it for reading Gmail messages.)
About these ads
Categories: python Tags: , ,
  1. No comments yet.
  1. January 20, 2013 at 12:24

Leave a Reply

Please log in using one of these methods to post your comment:

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

Follow

Get every new post delivered to your Inbox.

Join 72 other followers

%d bloggers like this: