Mail.send_message()   A
last analyzed

Complexity

Conditions 1

Size

Total Lines 13
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1.2963

Importance

Changes 0
Metric Value
eloc 6
dl 0
loc 13
ccs 1
cts 3
cp 0.3333
rs 10
c 0
b 0
f 0
cc 1
nop 3
crap 1.2963
1
#!/usr/bin/python
2
# -*- coding: utf-8 -*-
3 1
from smtplib import SMTP, SMTPAuthenticationError
4
5 1
from kuon.watcher import Settings
6
7
8 1
class InvalidSMTPSettingsException(Exception):
9 1
    pass
10
11
12 1
class InvalidMailSettingsException(Exception):
13 1
    pass
14
15
16 1
class Mail(object):
17
    """
18
    Class to notify the user via mail.
19
    """
20
21 1
    def __init__(self) -> None:
22
        """Initializing action. Validate SMTP connection and user settings"""
23
        self._smtp = SMTP(host=Settings.Notification.Mail.smtp_server, port=Settings.Notification.Mail.smtp_port)
24
        self._smtp.ehlo()
25
        self._smtp.starttls()
26
27
        # status code 250 is OK
28
        response = self._smtp.noop()
29
        if not response[0] == 250:
30
            raise InvalidSMTPSettingsException('Invalid SMTP Server settings')
31
32
        try:
33
            self._smtp.login(Settings.Notification.Mail.sender_mail, Settings.Notification.Mail.sender_pass)
34
        except SMTPAuthenticationError:
35
            raise InvalidMailSettingsException('Invalid user credentials for the SMTP server')
36
37 1
    def __del__(self) -> None:
38
        """Destructor"""
39
        self._smtp.close()
40
41 1
    def send_message(self, subject: str, text: str) -> None:
42
        """Send a mail to the configured mail
43
44
        :type subject:
45
        :type text:
46
        :return:
47
        """
48
        text = '\r\n'.join(['To: %s' % Settings.Notification.Mail.recipient_mail,
49
                            'From: %s' % Settings.Notification.Mail.sender_mail,
50
                            'Subject: %s' % subject,
51
                            '', text])
52
53
        self._smtp.sendmail(Settings.Notification.Mail.sender_mail, Settings.Notification.Mail.recipient_mail, text)
54