Archive

Posts Tagged ‘gmail’

Check Gmail for new messages

September 8, 2012 2 comments

Problem
I want to check my new Gmail messages periodically. When I get a message from a specific sender (with a specific Subject), I want to trigger some action. How to do that?

Solution
Fortunately, there is an atom feed of unread Gmail messages at https://mail.google.com/mail/feed/atom. All you have to do it is visit this page, send your login credentials, fetch the feed and process it.

import urllib2

FEED_URL = 'https://mail.google.com/mail/feed/atom'

def get_unread_msgs(user, passwd):
    auth_handler = urllib2.HTTPBasicAuthHandler()
    auth_handler.add_password(
        realm='New mail feed',
        uri='https://mail.google.com',
        user='{user}@gmail.com'.format(user=user),
        passwd=passwd
    )
    opener = urllib2.build_opener(auth_handler)
    urllib2.install_opener(opener)
    feed = urllib2.urlopen(FEED_URL)
    return feed.read()

##########

if __name__ == "__main__":
    import getpass

    user = raw_input('Username: ')
    passwd = getpass.getpass('Password: ')
    print get_unread_msgs(user, passwd)

For reading XML I use the untangle module:

import untangle    # sudo pip install untangle

xml = get_unread_msgs(USER, PASSWORD)
o = untangle.parse(xml)
try:
    for e in o.feed.entry:
        title = e.title.cdata
        print title
except IndexError:
    pass    # no new mail

Links

Categories: python Tags: , , , ,

Send e-mails via Gmail

February 19, 2011 1 comment

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.)
Categories: python Tags: , ,