download gmail attachment in python

How to Download Attachment from Gmail Using Python

Sometimes you may need to download attachment from Gmail programmatically. In this article, we will learn how to download attachment from Gmail using python. You can use it to download attachments from your python script, application or service.


How to Download Attachment from Gmail Using Python

Here are the steps to download attachment from Gmail using Python.

Create an empty python file download_attachment.py.

$ vi download_attachment.py

Add the following lines to it.

print 'Proceeding'

import email
import getpass
import imaplib
import os
import sys

userName = 'yourgmail@gmail.com'
passwd = 'yourpassword'
directory = '/full/path/to/the/directory'


detach_dir = '.'
if 'DataFiles' not in os.listdir(detach_dir):
    os.mkdir('DataFiles')



try:
    imapSession = imaplib.IMAP4_SSL('imap.gmail.com')
    typ, accountDetails = imapSession.login(userName, passwd)
    if typ != 'OK':
        print 'Not able to sign in!'
        raise

    imapSession.select('[Gmail]/All Mail')
    typ, data = imapSession.search(None, 'ALL')
    if typ != 'OK':
        print 'Error searching Inbox.'
        raise


    for msgId in data[0].split():
        typ, messageParts = imapSession.fetch(msgId, '(RFC822)')
        if typ != 'OK':
            print 'Error fetching mail.'
            raise

        emailBody = messageParts[0][1]
        mail = email.message_from_string(emailBody)
        for part in mail.walk():
            if part.get_content_maintype() == 'multipart':
                continue
            if part.get('Content-Disposition') is None:
                continue
            fileName = part.get_filename()

            if bool(fileName):
                filePath = os.path.join(detach_dir, 'DataFiles', fileName)
                if not os.path.isfile(filePath) :
                    print fileName
                    fp = open(filePath, 'wb')
                    fp.write(part.get_payload(decode=True))
                    fp.close()
    imapSession.close()
    imapSession.logout()

    print 'Done'


except :
    print 'Not able to download all attachments.'

Let us look at the above code in detail.

First, we import the required modules to connect to Gmail account. Next, we save Gmail username and password. We also store the path to directory where we need to download & store attachment. Next, we create a folder DataFiles where we will be downloading the attachments to, if it doesn’t exist.

Then we use imaplib module to log into Gmail using the username and password stored earlier. Once you have logged in, we run a search in our Inbox for All Mails and store the result in data object. Then we loop through the data object to get each email’s contents. Within each email’s contents, we fetch the attachment using its content type content disposition. We use it to get the attachment’s file name. We create a local file in DataFiles directory, and write the contents of each email’s attachment into it.

Lastly, we close the imap session and logout.

Save and close the file.

Make the file executable, with the following command.

$ sudo chmod +x download_attachment.py

Run the python file using the following command.

$ python download_attachment.py

Also read:

How to Read Line by Line Into Python List
How to Backup WordPress into GitHub
How to WordPress to Google Drive
How to Print Without Newline or Whitespace in Python
How to Convert String Representation into List

2 thoughts on “How to Download Attachment from Gmail Using Python

  1. Thanks much for posting this.

    I read somewhere that google changed their policy so that, as of May 31, 2022, they no longer allow 3rd party apps (like Python) to access gmails. Have you run into this issue? When I run your code (after inserting my credentials), I can not get by the imapSession.login statement.

Leave a Reply

Your email address will not be published. Required fields are marked *