|
| 1 | +# coding: utf-8 |
| 2 | +import os |
| 3 | +import configparser |
| 4 | +import email |
| 5 | +from email.header import decode_header |
| 6 | +import subprocess |
| 7 | + |
| 8 | +from imapclient import IMAPClient |
| 9 | + |
| 10 | +class EmailConfig: |
| 11 | + def __init__(self, configpath, debug=False): |
| 12 | + self.configpath = configpath |
| 13 | + self.config = self._get_config() |
| 14 | + self.debug=debug |
| 15 | + |
| 16 | + def _get_config(self): |
| 17 | + config = configparser.ConfigParser() |
| 18 | + config.read(self.configpath) |
| 19 | + return config |
| 20 | + |
| 21 | + def get_access_token(self, section, refresh=False): |
| 22 | + config = self.config |
| 23 | + if refresh: |
| 24 | + return self.refresh_access_token(section) |
| 25 | + self.access_token = config[section]['access_token'] |
| 26 | + return self.access_token |
| 27 | + |
| 28 | + def refresh_access_token(self, section): |
| 29 | + config = self.config |
| 30 | + self.user = config[section]['user'] |
| 31 | + client_id = config[section]['client_id'] |
| 32 | + client_secret = config[section]['client_secret'] |
| 33 | + refresh_token = config[section]['refresh_token'] |
| 34 | + # gmail oauth2.py is written for python 2 |
| 35 | + ps = subprocess.run([ |
| 36 | + os.path.join(os.path.dirname(__file__), './gmail/oauth2.py'), |
| 37 | + '--user={}'.format(self.user), |
| 38 | + '--client_id={}'.format(client_id), |
| 39 | + '--client_secret={}'.format(client_secret), |
| 40 | + '--refresh_token={}'.format(refresh_token)], |
| 41 | + stdout=subprocess.PIPE) |
| 42 | + access_token = ps.stdout.decode('utf-8').split('\n')[0].split(':')[1] |
| 43 | + if self.debug: |
| 44 | + print('접근 토큰: {}'.format(access_token)) |
| 45 | + |
| 46 | + # update config file |
| 47 | + config[section]['access_token'] = access_token |
| 48 | + self.update_config(verbose=self.debug) |
| 49 | + |
| 50 | + self.access_token = access_token |
| 51 | + return access_token |
| 52 | + |
| 53 | + def update_config(self, verbose=False): |
| 54 | + config = self.config |
| 55 | + with open(self.configpath, 'w') as cf: |
| 56 | + config.write(cf) |
| 57 | + if verbose: |
| 58 | + print('Config file {} updated.'.format(self.configpath)) |
| 59 | + |
| 60 | + |
| 61 | +class EmailClient: |
| 62 | + def __init__(self, |
| 63 | + host, |
| 64 | + port=None, |
| 65 | + use_uid=True, |
| 66 | + ssl=False, |
| 67 | + stream=False, |
| 68 | + ssl_context=None, |
| 69 | + timeout=None, |
| 70 | + method=None, |
| 71 | + debug=False): |
| 72 | + self.debug = debug |
| 73 | + self._imapclient = IMAPClient(host, ssl=ssl) |
| 74 | + if method: |
| 75 | + if 'oauth2' in method: |
| 76 | + oauth2_config = method['oauth2'] |
| 77 | + self.mailconfig = EmailConfig(oauth2_config['configfile'], |
| 78 | + debug=self.debug) |
| 79 | + self.mailconfig.get_access_token('GMAIL', refresh=True) |
| 80 | + login_result = self.oauth2_login(self.mailconfig.user, |
| 81 | + self.mailconfig.access_token) |
| 82 | + print(login_result) |
| 83 | + |
| 84 | + def oauth2_login(self, user, access_token): |
| 85 | + result = self._imapclient.oauth2_login(user, access_token) |
| 86 | + if 'Success' in result[0].decode('utf-8'): |
| 87 | + self.select_folder() |
| 88 | + return result |
| 89 | + |
| 90 | + def logout(self): |
| 91 | + return self._imapclient.logout() |
| 92 | + |
| 93 | + def select_folder(self, folder='INBOX', readonly=True): |
| 94 | + return self._imapclient.select_folder(folder, readonly=readonly) |
| 95 | + |
| 96 | + def search(self, criteria, charset='utf-8'): |
| 97 | + message_ids = self._imapclient.search(criteria, charset=charset) |
| 98 | + return message_ids |
| 99 | + |
| 100 | + def get_messages(self, message_ids): |
| 101 | + raw_messages = self._imapclient.fetch(message_ids, ['BODY[]']) |
| 102 | + messages=[] |
| 103 | + for mid, content in raw_messages.items(): |
| 104 | + body = email.message_from_bytes(content[b'BODY[]']) |
| 105 | + messages.append((mid, body)) |
| 106 | + return messages |
| 107 | + |
| 108 | + def get_subjects(self, message_ids): |
| 109 | + messages= self.get_messages(message_ids) |
| 110 | + subject_list = [] |
| 111 | + for mid, msg in messages: |
| 112 | + message_header = dict() |
| 113 | + message_header['ID'] = mid |
| 114 | + message_header['FROM'] = self._decode_header(msg.get('FROM')) |
| 115 | + message_header['Subject'] = self._decode_header(msg.get('Subject'))[0] |
| 116 | + subject_list.append(message_header) |
| 117 | + return subject_list |
| 118 | + |
| 119 | + def _decode_header(self, header): |
| 120 | + content_list = [] |
| 121 | + for field in email.header.decode_header(header): |
| 122 | + #if field is None: continue |
| 123 | + content, encoding = field |
| 124 | + if isinstance(content, bytes): |
| 125 | + content = content.decode(encoding if encoding else 'utf-8') |
| 126 | + content_list.append(content) |
| 127 | + return content_list |
0 commit comments