A Pythonic interface for Google Mail

Related tags

Email gmail
Overview

GMail for Python

A Pythonic interface to Google's GMail, with all the tools you'll need. Search, read and send multipart emails, archive, mark as read/unread, delete emails, and manage labels.

This library is still under development, so please forgive some of the rough edges

Heavily inspired by Kriss "nu7hatch" Kowalik's GMail for Ruby library

Author

Installation

For now, installation is manual (pip support not yet implemented) and the only requirement is to use Python 2 (2.7+ to be precise):

git clone git://github.com/charlierguo/gmail.git

Features

  • Search emails
  • Read emails
  • Emails: label, archive, delete, mark as read/unread/spam, star
  • Manage labels

Basic usage

To start, import the gmail library.

import gmail

Authenticating gmail sessions

To easily get up and running:

import gmail 

g = gmail.login(username, password)

Which will automatically log you into a GMail account. This is actually a shortcut for creating a new Gmail object:

from gmail import Gmail

g = Gmail()
g.login(username, password)
# play with your gmail...
g.logout()

You can also check if you are logged in at any time:

g = gmail.login(username, password)
g.logged_in # Should be True, AuthenticationError if login fails

OAuth authentication

If you have already received an OAuth2 access token from Google for a given user, you can easily log the user in. (Because OAuth 1.0 usage was deprecated in April 2012, this library does not currently support its usage)

gmail = gmail.authenticate(username, access_token)

Filtering emails

Get all messages in your inbox:

g.inbox().mail()

Get messages that fit some criteria:

g.inbox().mail(after=datetime.date(2013, 6, 18), before=datetime.date(2013, 8, 3))
g.inbox().mail(on=datetime.date(2009, 1, 1)
g.inbox().mail(sender="[email protected]") # "from" is reserved, use "fr" or "sender"
g.inbox().mail(to="[email protected]")

Combine flags and options:

g.inbox().mail(unread=True, sender="[email protected]")

Browsing labeled emails is similar to working with your inbox.

g.mailbox('Urgent').mail()

Every message in a conversation/thread will come as a separate message.

g.inbox().mail(unread=True, before=datetime.date(2013, 8, 3) sender="[email protected]")

Working with emails

Important: calls to mail() will return a list of empty email messages (with unique IDs). To work with labels, headers, subjects, and bodies, call fetch() on an individual message. You can call mail with prefetch=True, which will fetch the bodies automatically.

unread = g.inbox().mail(unread=True)
print unread[0].body
# None

unread[0].fetch()
print unread[0].body
# Dear ...,

Mark news past a certain date as read and archive it:

emails = g.inbox().mail(before=datetime.date(2013, 4, 18), sender="[email protected]")
for email in emails:
    email.read() # can also unread(), delete(), spam(), or star()
    email.archive()

Delete all emails from a certain person:

emails = g.inbox().mail(sender="[email protected]")
for email in emails:
    email.delete()

You can use also label method instead of mailbox:

g.label("Faxes").mail()

Add a label to a message:

email.add_label("Faxes")

Download message attachments:

for attachment in email.attachments:
    print 'Saving attachment: ' + attachment.name
    print 'Size: ' + str(attachment.size) + ' KB'
    attachment.save('attachments/' + attachment.name)

There is also few shortcuts to mark messages quickly:

email.read()
email.unread()
email.spam()
email.star()
email.unstar()

Roadmap

Copyright

  • Copyright (c) 2013 Charlie Guo

See LICENSE for details.

Comments
  • Added attachments

    Added attachments

    Added two lines to Message class to support attachments and an Attachment class to represent attachment objects. Attachments to an email are stored in an array (message.attachments). Attachment objects have name and size (kilobytes) properties, and their associated files can be saved to disk using the save() function, which optionally takes a path to save the file to. I updated the README to show capabilities, though you very well might want to represent the information differently.

    opened by robertf224 5
  • Detecting empty sets

    Detecting empty sets

    I decided to write a little email filter to run on my vps and I ran into an interesting problem:

    Traceback (most recent call last): File "mailfilter.py", line 19, in mail.read() File "/usr/local/lib/python2.7/dist-packages/gmail-0.0.5-py2.7.egg/gmail/message.py", line 41, in read self.gmail.imap.uid('STORE', self.uid, '+FLAGS', flag) File "/usr/lib/python2.7/imaplib.py", line 760, in uid typ, dat = self._simple_command(name, command, *args) File "/usr/lib/python2.7/imaplib.py", line 1070, in _simple_command return self._command_complete(name, self._command(name, *args)) File "/usr/lib/python2.7/imaplib.py", line 905, in _command_complete raise self.error('%s command error: %s %s' % (name, typ, data)) imaplib.error: UID command error: BAD ['Could not parse command']

    https://gist.github.com/anonymous/bd96cbcd768ce9c2647d This is my code.

    The problem seems to be that after running the filter once, it works as expected. The unwanted behaviour pops up if you run it multiple times if there are no items left matching the criteria, instead of holding 0 or None emails contains 1 message object, which I checked many times against my actual gmail account is not there. This falls automatically through the len() check and causes problems if you start calling methods on this "fake" message object. With message_id = None and no uid.

    opened by daemonfire300 3
  • Nothing returned at all in email

    Nothing returned at all in email

    Here is what is some of the output

    ['body', 'delivered_to', 'fr', 'uid', 'thread', 'thread_id', 'cc', 'labels', 'mailbox', 'to', 'flags', 'sent_at', 'message', 'subject', 'message_id', 'gmail'] [None, None, None, '161464', [], None, None, [], <gmail.mailbox.Mailbox instance at 0x1049179e0>, None, [], None, None, None, None, <gmail.gmail.Gmail instance at 0x1049173b0>] <gmail.message.Message instance at 0x10492ee60>

    Here is the code I am using... I dont think I am doing anything wrong. logged_in is returning true so it appears I am authenticated.

    !/usr/bin/python

    from gmail import Gmail import datetime

    g = Gmail()

    g.login("noybusername","noybpassword") emails = g.inbox().mail(fr="[email protected]") print(g.logged_in) print(emails[0].uid) print(emails[0].fr) for email in emails: print(email.dict.keys()) print(email.dict.values()) print(email)

    g.logout()

    opened by godratio 3
  • Readability improvements

    Readability improvements

    Hi Charlie,

    Cool project!

    I quickly went through the code to familiarise myself with it and decided to make some minor changes to improve the overall readability so that it is easier for people to navigate around it. Let me know what you think!

    opened by AnSavvides 2
  • Add hook to avoid parsing attachments

    Add hook to avoid parsing attachments

    This pull request includes a new exception type to raise when attachment parsing does not work and a hook to ignore attachment parsing entirely as a work-around. There's a little bit of PEP8 cleanup as well. Not sure anyone else will actually need this but I figured I'd make it available as a result of running into an exception like the following:

      File "/path/venv/lib/python2.7/site-packages/gmail/mailbox.py", line 74, in mail
        self.messages.update(self.gmail.fetch_multiple_messages(messages_dict))
      File "/path/venv/lib/python2.7/site-packages/gmail/gmail.py", line 156, in fetch_multiple_messages
        messages[uid].parse(raw_message)
      File "/path/venv/lib/python2.7/site-packages/gmail/message.py", line 173, in parse
        if not isinstance(attachment, basestring) and attachment.get('Content-Disposition') is not None
      File "/path/venv/lib/python2.7/site-packages/gmail/message.py", line 223, in __init__
        self.size = int(round(len(self.payload)/1000.0))
    TypeError: object of type 'NoneType' has no len()
    
    opened by tclancy 1
  • How to retrieve mail read/unread status ?

    How to retrieve mail read/unread status ?

    I am trying to retrieve read/unread status of mail using emails[0].is_read. It returns ">" for all emails whether its read or unread.

    Also tried with emails[0].read. But it also returns ">".

    Please help

    opened by KartikDomadiya 1
  • fix a bug when content of attachment is None (strange bug with email for...

    fix a bug when content of attachment is None (strange bug with email for...

    fix a bug when content of attachment is None (strange bug with email forward)

    I should fix the problem by allowing attachments like this one but I ddon't have time right now

    --004_AED2489C945A0F43BAB44072BC97FA211A64EFECTOREXCHANGE01co Content-Type: message/rfc822 Content-Disposition: attachment; creation-date="Thu, 20 Mar 2014 19:26:43 GMT"; modification-date="Thu, 20 Mar 2014 19:26:43 GMT" ....

    opened by chocobn69 1
  • Fetch full thread (sent and received) for a received message

    Fetch full thread (sent and received) for a received message

    I wanted the ability to fetch a full thread as it appears in the gmail interface (both sent and received), so I added fetch_thread() for a message. It caches the messages in the appropriate Mailbox.messages as well. It only works if called on a message that was sent to the user, not on a sent message. If there's interest I can make it more flexible. Perhaps a Thread object that wraps all emails? Maybe that's too much.

    On another note, the idea of there being a current_mailbox for a Gmail object caused problems for me - that state can change in unpredictable ways. It seems to me that any function that involves a mailbox should somehow take an arg for it rather than change something that's hard to follow. I can make an issue and work on that too if you want.

    opened by pgwhalen 1
  • Changing link references to be proper markup

    Changing link references to be proper markup

    These are some minor changes to the README so that links use proper markup.

    For example, this used to be: Charlie Guo [https://github.com/charlierguo]

    Now looks like: Charlie Guo

    opened by AnSavvides 1
  • Added setup.py file

    Added setup.py file

    I put your information into the setup.py file, but obviously didn't have your e-mail address. This way you can just do 'python setup.py install', even if you're not going to push to pypi. Could be handy for people trying it out.

    opened by danudey 1
  • Force connection over `imap.gmail.com`s IPv4 address

    Force connection over `imap.gmail.com`s IPv4 address

    This should allow us to login to gmail on machines that use IPv6, by forcing the use of IPv4

    See https://blog.zensoftware.co.uk/2016/05/13/gmail-blocking-mdaemon-email-arriving-via-ipv6/

    opened by johnspicer 0
  • Authentication error

    Authentication error

    AuthenticationError                       Traceback (most recent call last)
    <ipython-input-3-69ade5292074> in <module>()
    ----> 1 g.login ('**********', '**********')
    
    /home/debdut/Code/workspace/gmail/gmail/gmail.pyc in login(self, username, password)
        104                 self.fetch_mailboxes()
        105         except imaplib.IMAP4.error:
    --> 106             raise AuthenticationError
        107 
        108 
    
    AuthenticationError: 
    

    I also got an email that Google is blocking the login. How to fix it? Note: I have replaced my username password with *'s.

    opened by Debdut 4
  • Fetching Unread Emails removes Inbox label

    Fetching Unread Emails removes Inbox label

    unread = g.inbox().mail(unread=True)
    print unread[0].body
    

    This works once, but after that the email moves all the emails to All Mails from Inbox and the list becomes empty.

    opened by RohitJacob 0
Owner
Charlie Guo
Charlie Guo
A Python Mail Server

Salmon - A Python Mail Server Download: https://pypi.org/project/salmon-mail/ Source: https://github.com/moggers87/salmon Docs: https://salmon-mail.re

Matt Molyneaux 582 Dec 30, 2022
A light-weight, modular, message representation and mail delivery framework for Python.

Marrow Mailer A highly efficient and modular mail delivery framework for Python 2.6+ and 3.2+, formerly called TurboMail. © 2006-2019, Alice Bevan-McG

Marrow Open Source Collective 255 Dec 28, 2022
Fastapi mail system sending mails(individual, bulk) attachments(individual, bulk)

Fastapi-mail The fastapi-mail simple lightweight mail system, sending emails and attachments(individual && bulk) ?? Installation $ pip install fastap

Sabuhi 399 Dec 29, 2022
SMTP checker to check Mail Access via SMTP

SMTP checker to check Mail Access via SMTP with easy usage ! Medusa has been written and tested with Python 3.8. It should run on any OS as long as Python and all dependencies are installed.

h3x0 23 Dec 5, 2022
A Discord Mod Mail bot made in python

Fish-Mail The mod mail bot for Fish Hosting Note: You are not allowed to remove the names in the credit command Note: If you want any ideas/commands a

null 28 Aug 30, 2022
Django module to easily send templated emails using django templates, or using a transactional mail provider (mailchimp, silverpop, etc.)

Django-Templated-Email Info: A Django oriented templated email sending class Author: Bradley Whittington (http://github.com/bradwhittington, http://tw

Vinta Software 659 Dec 27, 2022
You take an email and password from the combo list file and check it on mail.com

Brute-Force-mail tool information: Combo Type: email:pass Domains: All domains of the site Url: https://www.mail.com Api: ☑️ Proxy: No ☑️ The correct

null 6 Jun 5, 2022
spam_box is a self hosted temp mail service by hacksec

spam_box spam_box is a self hosted temp mail service by hacksec Requirement python3 open port 25 and 6660 root access in a vps How to install in linux

ScRiPt1337 25 Dec 14, 2022
This simple python script uses cv2 to create and mail certificates to participants of workshops.

This simple python script uses cv2 to create and mail certificates to participants of workshops. Just collect the names and email ids of participants in a csv file (i used google docs), and place it in the project folder as given and run the script! Make sure to have 'Allow less secured apps' enabled for your gmail for smtp auth!

Sounder Rajendran 0 Dec 19, 2022
ghotok mail - lets you find available contact email addresses from target website

ghotok-mail ghotok mail - lets you find available contact email addresses from target website git clone https://github.com/josifkhan/ghotok-mail cd gh

Md Josif Khan 3 Mar 14, 2022
A python script that helps you understand why your E-Mail ended up in Spam

decode-spam-headers.py Whether you are trying to understand why a specific e-mail ended up in SPAM/Junk for your daily Administrative duties or for yo

Mariusz Banach 316 Jan 5, 2023
📧 CLI to deduplicate mails from mail boxes.

Mail Deduplicate Command-line tool to deduplicate mails from a set of boxes. Stable release: Development: Features Duplicate detection based on cherry

Kevin Deldycke 134 Dec 14, 2022
Yahoo Mail Validator For Python

Validator Validator helps to know if the mail is valid or not Installation Install The libraries pip install requests bs4 colorama Usage Create a new

Mr Python 3 Mar 12, 2022
GMailBomber is a form of Internet abuse which is perpetrated through the sending of massive volumes of email to a specific email address with the goal of overflowing the mailbox and overwhelming the mail server hosting the address, making it into some form of denial of service attack.

GMailBomber is a form of Internet abuse which is perpetrated through the sending of massive volumes of email to a specific email address with the goal of overflowing the mailbox and overwhelming the mail server hosting the address, making it into some form of denial of service attack.

Muneeb 5 Nov 13, 2022
Automatically Send Custom Named Certificates via Mail

Welcome to Certificate Launchpad ?? Automatically Send Custom Named Certificates via Email Intro After any event, sending certificates to attendees or

Dc7 16 Oct 16, 2022
This is the mail server that handles responses from the Contact Form

mailserver About This is the mail server that handles responses from the Contact Form Contributors ✨ Thanks goes to these wonderful people (emoji key)

IoLang 3 Jan 3, 2022
An automation program that checks whether email addresses are real, whether they exist and whether they are a validated mail

Email Validator It is an automation program that checks whether email addresses are real, whether they exist and whether they are a validated mail. Re

Ender MIRIZ 4 Dec 22, 2021
Send Multiple Mail From List With Python

Send Multiple Mail From List With Python You can send multiple e-mail using HTML themes with Python. Here is the e-mail information to be sent. #The m

Mücahid Eker 1 Dec 23, 2021
A research into mail services used by different business sectors.

A research into mail services used by different business sectors. Data, scripts and results available.

Focus Chen 1 Dec 24, 2021