Completed
Pull Request — master (#350)
by Tomaz
02:35
created

SendEmailAction.run()   B

Complexity

Conditions 6

Size

Total Lines 28

Duplication

Lines 0
Ratio 0 %
Metric Value
cc 6
dl 0
loc 28
rs 7.5385
1
import httplib
2
3
import requests
4
5
from st2actions.runners.pythonrunner import Action
6
7
__all__ = [
8
    'SendEmailAction'
9
]
10
11
SEND_EMAIL_API_URL = 'https://api.mailgun.net/v2/%(domain)s/messages'
12
13
14
class SendEmailAction(Action):
15
    def run(self, sender, recipient, subject, text=None, html=None):
16
        if not text and not html:
17
            raise ValueError('Either "text" or "html" or both arguments need to be provided')
18
19
        domain = self.config['domain']
20
        api_key = self.config['api_key']
21
22
        data = {
23
            'from': sender,
24
            'to': recipient,
25
            'subject': subject
26
        }
27
28
        if text:
29
            data['text'] = text
30
31
        if html:
32
            data['html'] = html
33
34
        api_url = SEND_EMAIL_API_URL % {'domain': domain}
35
        response = requests.post(api_url, auth=('api', api_key), data=data)
36
37
        if response.status_code != httplib.OK:
38
            msg = ('Failed to send message (status_code=%s): %s' %
39
                   (response.status_code, response.text))
40
            raise Exception(msg)
41
42
        return True
43