Skip to content

Commit f261ef8

Browse files
committed
의존 패키지 추가
1 parent c3867a1 commit f261ef8

6 files changed

Lines changed: 140 additions & 3 deletions

File tree

‎bigpython/mail.py‎

Lines changed: 127 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,127 @@
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

‎bigpython/office/excel.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
# coding: utf-8
12
import pandas as pd
23

34
def Excel(io, sheetname=None, header=0):

‎bigpython/office/word.py‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
1+
# coding: utf-8
12
import docx
23
import pandas as pd
4+
35
from .excel import Excel
4-
import types
6+
57

68
def Word(filepath_or_buffer=None):
79
"""

‎bigpython/webscrap/html.py‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,12 @@
11
# coding: utf-8
22
from urllib.parse import urlparse
33
import re
4-
import pandas as pd
5-
from bs4 import BeautifulSoup
64
import importlib
75
from . import io
86

7+
import pandas as pd
8+
from bs4 import BeautifulSoup
9+
910
def get_soup(src, encoding='utf-8'):
1011
"""Returns BeautifulSoup from URL or file
1112

‎bigpython/webscrap/io.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
1+
# coding: utf-8
12
import sys
23
from urllib.parse import urlparse, unquote, unquote_plus
4+
35
import requests
46

57
def snapshot_webpage(url, filename=None, mode='wb', data=None):

‎setup.py‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,10 @@
99
packages=['bigpython', 'bigpython.webscrap', 'bigpython.office'],
1010
package_dir={'bigpython':'bigpython'},
1111
install_requires=[
12+
'pandas',
13+
'beautifulsoup4',
14+
'selenium',
15+
'requests',
1216
'imapclient',
1317
'python-docx'
1418
])

0 commit comments

Comments
 (0)