test_get_mail.py 4.68 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
# -*- coding: utf-8 -*-
"""
Created on Sat Oct  3 19:52:04 2020

@author: josep
"""
'''
Mail handler for today at earlham.
'''

import imaplib
import json 
import email
from email.header import decode_header
import webbrowser
import os
from datetime import datetime

with open('../../../ECHackersBotCreds/credentials.json') as file:
    credentials = json.load(file)

account_email='earlhamhackerscontrol@gmail.com'
account_password = credentials['email_password']


daily_mail_from = 'ejnislam18@gmail.com'
daily_mail_name = '[Today-at-Earlham] Daily Mailing'
annoucement_delimeter = '------------------------------'
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul','Aug','Sep','Oct','Nov','Dec']

def get_today_at_school(account_email, account_password, daily_mail_from = 'ejnislam18@gmail.com', daily_mail_name = '[Today-at-Earlham] Daily Mailing', annoucement_delimeter= '------------------------------'):
    # create an IMAP4 class with SSL 
    imap = imaplib.IMAP4_SSL("imap.gmail.com")
    # authenticate
    imap.login(account_email, account_password)
    
    status, messages = imap.select("INBOX")
    # number of top emails to fetch
    N = 3
    # total number of emails
    messages = int(messages[0])
    
    announcements = []
    for i in range(messages, messages-N, -1):
        # fetch the email message by ID
        res, msg = imap.fetch(str(i), "(RFC822)")
        for response in msg:
            if isinstance(response, tuple):
                # parse a bytes email into a message object
                msg = email.message_from_bytes(response[1])
                # decode the email subject
                subject = decode_header(msg["Subject"])[0][0]
                date = msg.get('Date').split(' ')
                day, month, year = int(date[1]), date[2], date[3]
                if isinstance(subject, bytes):
                    # if it's a bytes, decode to str
                    subject = subject.decode()
                # email sender
                from_ = msg.get("From")
                today = datetime.today()
                if not (today.day == day and today.month == months.index(month)+1 and today.year == int(year)) or daily_mail_from not in from_ or daily_mail_name not in subject: # and the date isn't today
                    continue
                # if the email message is multipart
                if msg.is_multipart():
                    # iterate over email parts
                    for part in msg.walk():
                        # extract content type of email
                        content_type = part.get_content_type()
                        content_disposition = str(part.get("Content-Disposition"))
                        try:
                            # get the email body
                            body = part.get_payload(decode=True).decode()
                        except:
                            pass
                        if content_type == "text/plain" and "attachment" not in content_disposition:
                            # print text/plain emails and skip attachments
                            announcements=body.split(annoucement_delimeter)
                            
                        elif "attachment" in content_disposition:
                            pass
                else:
                    print('isn\'t multipart')
                    # extract content type of email
                    content_type = msg.get_content_type()
                    # get the email body
                    body = msg.get_payload(decode=True).decode()
                    if content_type == "text/plain":
                        # print only text email parts
                        pass
    if not len(announcements):
        return ([], [])
    announcements[0] = announcements[0][len("'---------- Forwarded message ---------\r\nFrom: Earlham College <webeditor@earlham.edu>\r\nDate: Fri, Oct 2, 2020 at 8:01 AM\r\nSubject: [Today-at-Earlham] Daily Mailing\r\nTo: <today-at-earlham@earlham.edu>\r\n\r\n\r\nToday@Earlham <http://earlham.edu/news/today/> for October 02, 2020\r\nView Online <http://earlham.edu/news/today/>     Submit Announcement\r\n<http://earlham.edu/news/today/submit/>\r\n")-1:]
    remote_accessible_annoucements = []
    in_person_annoucements = [] 
    for annoucement in announcements:
        annoucementl = annoucement.lower()
        if 'virtual' in annoucementl or 'zoom' in annoucementl or 'remote' in annoucementl or 'online' in annoucementl:
            remote_accessible_annoucements.append(annoucement)
        else:
            in_person_annoucements.append(annoucement)
    
    imap.close()
    imap.logout()
    return remote_accessible_annoucements, in_person_annoucements[:-1]
#print(get_today_at_school(account_email, account_password))