-
Notifications
You must be signed in to change notification settings - Fork 20
/
flask_mailgun.py
308 lines (255 loc) · 10.5 KB
/
flask_mailgun.py
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 27 21:48:14 2016
@author: richard, yunxi
"""
import requests
from flask import request
# For verification
import hashlib
import hmac
import os
import json
from collections import defaultdict
from decorator import decorator
from threading import Thread
from werkzeug.utils import secure_filename
class MailGunException(Exception):
pass
EXTENSIONS = {
"TEXT": ["txt", "md"],
"DOCUMENT": ["rtf", "odf", "ods", "gnumeric",
"abw", "doc", "docx", "xls", "xlsx", 'xlsb'],
"IMAGE": ["jpg", "jpeg", "jpe", "png", "gif", "svg", "bmp", "webp"],
"AUDIO": ["wav", "mp3", "aac", "ogg", "oga", "flac"],
"DATA": ["csv", "ini", "json", "plist", "xml", "yaml", "yml"],
"SCRIPT": ["js", "php", "pl", "py", "rb", "sh"],
"ARCHIVE": ["gz", "bz2", "zip", "tar", "tgz", "txz", "7z"]
}
ALL_EXTENSIONS = EXTENSIONS["TEXT"] \
+ EXTENSIONS["DOCUMENT"] \
+ EXTENSIONS["IMAGE"] \
+ EXTENSIONS["AUDIO"] \
+ EXTENSIONS["DATA"] \
+ EXTENSIONS["ARCHIVE"]
MAILGUN_API_URL = 'https://api.mailgun.net/v3'
@decorator
def async(f, *args, **kwargs):
# this is not thread safe at the moment
# TODO consider using celery or multiprocesing pool
thread = Thread(target=f, args=args, kwargs=kwargs)
thread.start()
return thread
class MailGun(object):
"""MailGun Class"""
app = None
mailgun_api = None
auto_reply = True
run_async = True
logger = None
_route = []
def __init__(self, app=None):
if app is not None:
self.init_app(app)
def init_app(self, app):
self.app = app
self.mailgun_api = MailGunAPI(app.config)
self._on_receive = []
self._on_attachment = []
# self.temp_file_dir = app.config['TEMP_FILE_DIR']
# self.allowed_extensions = app.config["ALLOWED_EXTENSIONS"]
def send_email(self, **kwargs):
if not self.mailgun_api:
raise ValueError('A valid app instance has not been provided')
default_from = self.app.config.get('MAILGUN_DEFAULT_FROM')
if default_from:
kwargs.setdefault('from', default_from)
return self.mailgun_api.send_email(**kwargs)
def create_route(self, dest='/messages/'):
"""Create the mailgun route and register endpoint with flask app
this needs to be done after `mailgun.app_init`
"""
# register the process_email endpoint with the flask app
@self.app.route(dest, methods=['POST'])
def mail_endpoint():
# Note: currently there is not an eay way to remove a route from flask
# app after creation. As a result, an extra if-clause is added here to
# facilitate the `destroy_route` function. For more information see:
# http://stackoverflow.com/questions/24129217/flask-delete-routes-added-with-add-url
if dest == self.mailgun_api.dest:
return self.process_email(request)
abort(404)
# register the endpoint route with mailgun
return self.mailgun_api.create_route(dest)
def destroy_route(self, dest):
""" Destroy routes from mailgun
Description:
Destroy the route from Mailgun, and remove the correspinding route
from the flask application.
Return:
a string that contains information of the operation results
"""
ret = self.mailgun_api.destroy_route(dest)
try:
self._route.remove(dest)
msg = "Successfully removed endpoint {}. \n".format(dest)
except ValueError:
msg = "Endpoint {} not found. \n".format(dest)
return msg + "Remote message from Mailgun: {}".format(ret)
def on_receive(self, func):
"""Register callback function with mailgun
`@mailgun.on_receive
def process_email(email)`
"""
self._on_receive.append(func)
return func
def on_attachment(self, func):
"""Register callback function with mailgun
`@mailgun.on_attachment
def process_attachment(email, filestorage)`
"""
self._on_attachment.append(func)
return func
def process_email(self, request):
"""Function to pass to endpoint for processing incoming email post
app.route('/incoming', methods=['POST'])(process_email)
"""
email = request.form
self.mailgun_api.verify_email(email)
# Process the attachments
for func in self._on_attachment:
if self.run_async:
func = async(func)
for attachment in request.files.values():
attachment.filename = secure_filename(attachment.filename)
func(email, attachment)
# data = attachment.stream.read()
# with open(attachment.filename, "w") as f:
# f.write(data)
# Process the email
for func in self._on_receive:
if self.run_async:
func = async(func)
func(email)
# log and notify
self.__log_status(request)
if self.auto_reply:
self.reply_sender(email)
return "OK"
def reply_sender(self, email, text=None):
timestamp = email.get("timestamp")
sender = email.get('from')
recipient = email.get('To')
subject = email.get('subject')
if text is None:
message = 'Hello {} \n Yum Yum! you feed me at {}.'
text = message.format(sender,
timestamp)
recipient = "%(route)s@%(domain)s" % self.mailgun_api.__dict__
self.send_email(**{'from': recipient,
'to': [sender],
'subject': subject,
'text': text})
def _is_allowed_file(self, f_name):
file_extension = os.path.splitext(f_name)[1].lower()
return file_extension in self.allowed_extensions
def __log_status(self, request):
if self.logger:
email = request.form
return self.logger.log({
"message": "Email received",
"sender": email.get("sender"),
"receiver": email.get("recipient"),
"timestamp": email.get("timestamp"),
"number_of_attachments": email.get("attachment-count"),
"attachment_names": request.files.keys()}, "Info")
class MailGunAPI(object):
def __init__(self, config):
self.domain = config['MAILGUN_DOMAIN']
self.api_key = config['MAILGUN_API_KEY']
self.api_url = config.get('MAILGUN_API_URL',
'https://api.mailgun.net/v2/')
self.route = config.get('MAILGUN_ROUTE', 'uploads')
self.host = config.get('MAILGUN_DOMAIN', self.domain)
if self.api_key is None:
raise MailGunException("No mailgun key supplied.")
def send_email(self, **kwargs):
files = kwargs.pop('files', [])
responce = requests.post(self.sendpoint,
data=kwargs,
files=files,
auth=self.auth)
responce.raise_for_status()
return responce
def list_routes(self):
request = requests.get(self.routepoint,
auth=self.auth)
return json.loads(request.text).get('items')
def route_exists(self, route):
routes = self.list_routes()
expression_action = defaultdict(list)
for r in routes:
expression_action[r['expression']].extend(r['actions'])
current_actions = expression_action[route['expression']]
return set(route['action']) <= set(current_actions)
def create_route(self, dest='/messages/', data=None,):
self.dest = dest
route = self._build_route()
# Create Route Only if it does not Exist # TODO should update?
if self.route_exists(route):
return None
else:
return requests.post(self.routepoint,
auth=self.auth,
data=data)
def destroy_route(self, dest):
route_id = self.get_route_id(self._build_route(dest))
if route_id:
ret = request.delete(self.api_url + route_id, auth=self.auth)
return ret["message"] if route_id else "Route not found"
def _build_route(self, dest=None):
""" Build a mailgun route dictionary
"""
if not dest:
dest = self.dest
action = "forward('http://{}{}".format(self.host, dest)
return {"priority": 0,
"description": "Sample route",
"expression": "match_recipient('%(route)s@%(domain)s')" % self.__dict__,
"action": [action, "stop()"]}
def get_route_id(self, route):
""" Get id of the route
Return: id of the route. None if not exist.
"""
routes = self.list_routes()
if routes:
id_table = dict([(r["expression"]+r["actions"], r["id"]) for r in routes])
return id_table.get(route["expression"]+route["action"]) if routes else None
def verify_email(self, email):
"""Check that the email post came from mailgun
see https://documentation.mailgun.com/user_manual.html#webhooks
"""
if self.api_key is None:
raise MailGunException("Mailbox Error: No MailGun API key is supplied.")
signature = email.get("signature")
token = email.get("token")
timestamp = email.get("timestamp")
if timestamp is None or token is None or signature is None:
raise MailGunException("Mailbox Error: credential verification failed.", "Not enough parameters")
signature_calc = hmac.new(key=self.api_key,
msg='{}{}'.format(timestamp, token),
digestmod=hashlib.sha256).hexdigest()
if signature != signature_calc:
raise MailGunException("Mailbox Error: credential verification failed.", "Signature doesn't match")
def api_route(self, *pieces):
pieces = [self.api_url] + [p for p in pieces]
return '/'.join(s.strip('/') for s in pieces)
@property
def sendpoint(self):
return self.api_route(self.domain, 'messages')
@property
def routepoint(self):
return self.api_route('routes')
@property
def auth(self):
return ('api', self.api_key)