Created
August 21, 2016 08:07
-
-
Save strycore/69b6dfd562fd5023e9e396872e028776 to your computer and use it in GitHub Desktop.
Download emails from an imap folder
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python3 | |
import os | |
import ssl | |
import imaplib | |
from configparser import ConfigParser | |
config_path = os.path.expanduser('~/.mailbot.conf') | |
parser = ConfigParser() | |
parser.read(config_path) | |
HOSTNAME = parser.get('imap', 'hostname') | |
LOGIN = parser.get('imap', 'login') | |
PASSWORD = parser.get('imap', 'password') | |
PORT = parser.get('imap', 'port') | |
FOLDER = parser.get('emails', 'folder') | |
DESTPATH = parser.get('emails', 'destpath') | |
ssl_context = ssl.create_default_context() | |
ssl_context.protocol = ssl.PROTOCOL_TLSv1 | |
ssl_context.check_hostname = False | |
ssl_context.verify_mode = ssl.CERT_NONE | |
mail = imaplib.IMAP4_SSL(HOSTNAME, PORT, ssl_context=ssl_context) | |
mail.login(LOGIN, PASSWORD) | |
_success, num_mails = mail.select(FOLDER) | |
_success, data = mail.search(None, 'ALL') | |
for num in data[0].split(): | |
_success, data = mail.fetch(num, '(RFC822)') | |
email_path = os.path.join(os.path.expanduser(DESTPATH), '{}.eml'.format(num.decode())) | |
with open(email_path, 'wb') as email_file: | |
email_file.write(data[0][1]) | |
mail.close() | |
mail.logout() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment