email.py 3.01 KB
Newer Older
1 2 3 4 5 6
# coding: utf-8
"""
Email notifications.
"""

from __future__ import absolute_import, print_function, unicode_literals
7
from builtins import str
Phyks's avatar
Phyks committed
8 9

import logging
10 11 12 13
import smtplib

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
Phyks's avatar
Phyks committed
14 15 16
from email.utils import formatdate, make_msgid

LOGGER = logging.getLogger(__name__)
17

Phyks's avatar
Phyks committed
18

19
def send_email(server, port, subject, _from, _to, txt, html, username=None, password=None):
Phyks's avatar
Phyks committed
20 21 22 23 24 25 26 27 28 29 30 31
    """
    Send an email

    :param server: SMTP server to use.
    :param port: SMTP port to use.
    :param subject: Subject of the email to send.
    :param _from: Email address of the sender.
    :param _to: List of email addresses of the receivers.
    :param txt: Text version of the message.
    :param html: HTML version of the message.
    """
    if not _to:
32 33 34 35
        LOGGER.warn("No recipients for the email notifications, aborting.")
        return

    server = smtplib.SMTP(server, port)
36 37
    if username or password:
        server.login(username or "", password or "")
38 39 40 41

    msg = MIMEMultipart('alternative')
    msg['Subject'] = subject
    msg['From'] = _from
Phyks's avatar
Phyks committed
42 43 44
    msg['To'] = ', '.join(_to)
    msg['Date'] = formatdate()
    msg['Message-ID'] = make_msgid()
45 46 47 48

    msg.attach(MIMEText(txt, 'plain', 'utf-8'))
    msg.attach(MIMEText(html, 'html', 'utf-8'))

Phyks's avatar
Phyks committed
49
    server.sendmail(_from, _to, msg.as_string())
50 51
    server.quit()

Phyks's avatar
Phyks committed
52

53
def send_notification(config, flats):
Phyks's avatar
Phyks committed
54 55 56 57 58 59
    """
    Send an email notification about new available flats.

    :param config: A config dict.
    :param flats: List of flats to include in the notification.
    """
60
    # Don't send an email if there are no new flats.
Phyks's avatar
Phyks committed
61
    if not flats:
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
        return

    txt = u'Hello dear user,\n\nThe following new flats have been found:\n\n'
    html = """
    <html>
      <head></head>
      <body>
        <p>Hello dear user!</p>
        <p>The following new flats have been found:

            <ul>
    """

    website_url = config["website_url"]

    for flat in flats:
78 79 80 81 82
        title = str(flat.title)
        flat_id = str(flat.id)
        area = str(flat.area)
        cost = str(flat.cost)
        currency = str(flat.currency)
83

Phyks's avatar
Phyks committed
84 85 86 87 88
        txt += (
            '- {}: {}#/flat/{} (area: {}, cost: {} {})\n'.format(
                title, website_url, flat_id, area, cost, currency
            )
        )
89 90 91 92 93 94 95 96 97 98

        html += """
            <li>
                <a href="{}#/flat/{}">{}</a>
                (area: {}, cost: {} {})
            </li>
        """.format(website_url, flat_id, title, area, cost, currency)

    html += "</ul>"

Phyks's avatar
Phyks committed
99 100 101 102 103
    signature = (
        u"\nHope you'll find what you were looking for.\n\nBye!\nFlatisfy"
    )
    txt += signature
    html += signature.replace('\n', '<br>')
104 105 106 107 108 109 110 111 112 113 114

    html += """</p>
      </body>
    </html>"""

    send_email(config["smtp_server"],
               config["smtp_port"],
               "New flats found!",
               config["smtp_from"],
               config["smtp_to"],
               txt,
115 116 117
               html,
               config.get("smtp_username"),
               config.get("smtp_password"))