Extract email attachments received in Thunderbird with Python

I posted a post Convert PDF attached to email to text format before, and it seems that it was quite popular.

I will write about the modified version.

In 18.4. mailbox — Mailbox operations in various formats

Great care must be taken when updating mailboxes that may be changed at the same time by some other process. The safest mailbox format for doing such tasks is Maildir, and try to avoid using a single file format like mbox for concurrent writes.

And

There are several variations of the mbox format, each claiming to overcome the shortcomings of the original format.

Because it was written like this, in PDF attached to email ..., it was read as Maildir format by Cygwin's procmail / fetchmail. The mbox format handled by Thunderbird can be read by Python's mailbox library (albeit in some dialects), so I'm using the official Python.org binary.

In Thunderbidr, the directory for saving mail is generated with 8 random characters, so it is necessary to rewrite that area.

#coding:utf-8

import os
import os.path
import sys

import email
import mailbox
import mimetypes

maildir =
'C:\\Users\\t.uehara\\AppData\\Roaming\\Thunderbird\\Profiles\\abcdef12.default\\Mail\\pop.example.com\\Inbox'

tempdir = 'C:\\Users\\t.uehara\\Downloads\\'

def extractMime(message):

    for part in message.walk():

        if part.get_content_maintype() == 'multipart':
            continue

        fname = part.get_filename()
        if fname != None:

            if fname.find(".zip") != -1:
                zipname = tempdir+fname

                #If the Zip file exists, skip the process
                if os.path.isfile(zipname) == False:
                    fp = open(zipname, 'wb')
                    fp.write(part.get_payload(decode=True))
                    fp.close()
                    print zipname

if __name__ == '__main__':

    for message in mailbox.mbox(maildir):
        extractMime(message)

In addition to saving the Zip file, you can also read the compressed log file and perform appropriate processing, but since the source code is a bit crowded, I will add it if there is a request in the comments etc. ..

Recommended Posts

Extract email attachments received in Thunderbird with Python
Email attachments using your gmail account in python.
[Automation] Extract the table in PDF with Python
Validate E-Mail with Python
Send email with Python
Send an email with Excel attached in Python
Send Japanese email with Python3
Scraping with selenium in Python
Scraping with chromedriver in python
Debugging with pdb in Python
Working with sounds in Python
Scraping with Selenium in Python
Send email in Python (Outlook)
Scraping with Tor in Python
Tweet with image in Python
Extract template of EML file saved from Thunderbird with python3.7
How to extract any appointment in Google Calendar with Python
Extract multiple list duplicates in Python
Number recognition in images with Python
Extract the xz file with python
Testing with random numbers in Python
GOTO in Python with Sublime Text 3
Working with LibreOffice in Python: import
[Automation] Extract Outlook appointments with Python
Scraping with Selenium in Python (Basic)
CSS parsing with cssutils in Python
Numer0n with items made in Python
Open UTF-8 with BOM in Python
Use rospy with virtualenv in Python3
Extract text from images in Python
Easy email sending with haste python3
Use Python in pyenv with NeoVim
Heatmap with Dendrogram in Python + matplotlib
Read files in parallel with Python
Password generation in texto with python
Use OpenCV with Python 3 in Window
Until dealing with python in Atom
[Python] Send an email with outlook
Get started with Python in Blender
Working with DICOM images in Python
Send email via gmail with Python 3.4.3.
Extract strings from files in Python
Spiral book in Python! Python with a spiral book! (Chapter 14 ~)
Try logging in to qiita with Python
Stress Test with Locust written in Python
Python3> in keyword> True with partial match?
Device monitoring with On-box Python in IOS-XE
Try working with binary data in Python
Draw Nozomi Sasaki in Excel with python
Tips for dealing with binaries in Python
Send email to multiple recipients in Python (Python 3)
Send email with SES in Python and short message with SMS on SNS
Display Python 3 in the browser with MAMP
Page cache in Python + Flask with Flask-Caching
Post Test 3 (Working with PosgreSQL in Python)
How to work with BigQuery in Python
Playing card class in Python (with comparison)
I tried sending an email with python.
How to extract polygon area in Python
Process multiple lists with for in Python
One liner webServer (with CGI) in python