Skip to content

Instantly share code, notes, and snippets.

@NicholasTurner23
Last active January 14, 2019 12:42
Show Gist options
  • Save NicholasTurner23/03ff2053ffd4704f714361a2ccf9ffac to your computer and use it in GitHub Desktop.
Save NicholasTurner23/03ff2053ffd4704f714361a2ccf9ffac to your computer and use it in GitHub Desktop.
Download email attachments from a specific email address in your inbox
from datetime import datetime
class Server(models.Model):
owner = models.CharField(max_length=100)
user_name = models.CharField(max_length=100)
password = models.CharField(max_length=100)
host = models.CharField(max_length=100)
status = models.BooleanField(default=True)
created_on = models.DateTimeField(auto_now=True)
@classmethod
def connect(cls):
data = cls.objects.filter(status=True).all()
hosts = []
for d in data:
host = imaplib.IMAP4_SSL(d.host)
host.login(d.user_name, d.password)
host.select() #Filter by INBOX, ALL
host.list() #Everything
hosts.append(host)
return hosts
@classmethod
def attachment(cls, host, emailid):
resp, data = host.fetch(emailid, "(BODY.PEEK[])")
email_body = data[0][1]
mail = email.message_from_string(email_body)
if mail.get_content_maintype() != 'multipart':
return
for part in mail.walk():
if part.get_content_maintype() != 'multipart' and part.get('Content-Disposition') is not None:
open('media/downloads/' + str(part.get_filename()), 'wb').write(part.get_payload(decode=True))
@classmethod
def download(cls):
hosts = cls.connect()
today = datetime.date.today()
//download from previous day
cutoff = today - timedelta(days=1)
if not hosts:
return 'Not a list'
else:
for host in hosts:
#download attachments sent from a specific address. To download everything, omit "'FROM', "email@address","
resp, items = host.search(None, 'FROM', "email@address", 'SINCE', cutoff.strftime('%d-%b-%Y'))
items = items[0].split()
for emailid in items:
cls.attachment(host=host, emailid=emailid)
@classmethod
def close_connection(cls):
data = cls.objects.filter(status=True).all()
for d in data:
host = imaplib.IMAP4_SSL(d.host)
host.login(d.user_name, d.password)
host.select()
host.logout()
return
def __unicode__(self):
return self.owner
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment