This repository has been archived by the owner on Jul 19, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMailer.py
80 lines (63 loc) · 2.8 KB
/
Mailer.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
"""
TODO logging
TODO message body
TODO hide psswd from ram, or at least somehow encrypt it
"""
import smtplib
from os.path import basename
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.utils import formatdate
from email.utils import make_msgid
from email.message import EmailMessage
from typing import List
import mimetypes
import logging
from FileType import PDF
import auth
class Mailer(object):
def __init__(self, logger: logging.getLogger):
self.log = logger
def send_mail(self, pdf: PDF=None):
msg = EmailMessage()
msg['Date'] = formatdate(localtime=True)
msg['Subject'] = 'New file on sps-prosek.cz'
msg['Reply-To'] = auth.Smtp.reply_to
# set the plain text body
msg.set_content('This is a plain text body.')
# now create a Content-ID for the image
# image_cid looks like <long.random.number@xyz.com>
# to use it as the img src, we don't need `<` or `>`
# so we use [1:-1] to strip them off
image_cid = make_msgid()[1:-1]
# if `domain` argument isn't provided, it will
# use your computer's name
# set an alternative html body
with open('email-template.html', 'r') as email_template:
email_message = email_template.read()
email_message = email_message.replace('{version_number}', str(pdf.get_version()))
email_message = email_message.replace('{day_name}', pdf.get_day_name())
email_message = email_message.replace('{image_cid}', image_cid)
email_message = email_message.replace('{author_name}', pdf.get_author())
email_message = email_message.replace('{unsubscribe_link}', auth.Smtp.unsubscribe)
email_message = email_message.replace('{repo_link}', auth.Smtp.repository)
msg.add_alternative(email_message, subtype='html')
# attach it
msg.get_payload()[1].add_related(pdf.get_as_image(), maintype='image', subtype='png', cid=image_cid)
# open connection to server and send the mail
self.log.debug('opening connection to SMTP server and sending emails')
with smtplib.SMTP('smtp.gmail.com', 587) as smtp:
smtp.starttls()
smtp.login(auth.Smtp.login, auth.Smtp.password)
smtp.sendmail(auth.Smtp.sender, self.get_recipients(), msg.as_string())
self.log.info('emails successfully sent')
def get_recipients(self)-> List[str]:
recipients = list()
with open('recipients', 'r') as rcps:
for r in rcps.readlines():
r = r.replace('\n', '')
self.log.info('adding %s to recipients', repr(r))
recipients.append(r)
return recipients