ticketfrei/sendmail.py

92 lines
2.8 KiB
Python
Raw Normal View History

2018-01-01 10:23:50 +00:00
#!/usr/bin/env python3
2018-03-28 18:24:21 +00:00
from config import config
2018-01-01 10:23:50 +00:00
from email.mime.text import MIMEText
2018-01-05 10:20:07 +00:00
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
2018-03-28 22:31:21 +00:00
import logging
from getpass import getuser
import smtplib
from socket import getfqdn
import ssl
2018-03-28 22:31:21 +00:00
2018-03-29 00:40:22 +00:00
logger = logging.getLogger(__name__)
2018-01-01 10:23:50 +00:00
2018-03-29 00:40:22 +00:00
2018-01-01 10:23:50 +00:00
class Mailer(object):
"""
Maintains the connection to the mailserver and sends text to users.
"""
2018-03-28 18:24:21 +00:00
def __init__(self):
2018-01-01 10:23:50 +00:00
"""
2018-01-05 10:20:07 +00:00
Creates an SMTP client to send a mail. Is called only once
when you actually want to send a mail. After you sent the
mail, the SMTP client is shut down again.
2018-01-01 10:23:50 +00:00
"""
# This generates the From address by stripping the part until the first
# period from the mail server address and won't work always.
self.fromaddr = config["mail"]["user"] + "@" + config["mail"]["mailserver"].partition(".")[2]
2018-01-01 10:23:50 +00:00
# starts a client session with the SMTP server
self.s = smtplib.SMTP(config["mail"]["mailserver"])
2018-03-28 22:31:21 +00:00
try:
context = ssl.create_default_context()
2018-03-28 22:39:45 +00:00
self.s.starttls(context=context)
except BaseException: # TODO: Amend specific exception
2018-03-28 22:39:45 +00:00
logger.error('StartTLS failed.', exc_info=True)
self.s.login(config["mail"]["user"], config["mail"]["passphrase"])
2018-01-01 10:23:50 +00:00
2018-01-05 10:20:07 +00:00
def send(self, text, recipient, subject, attachment=None):
2018-01-01 10:23:50 +00:00
"""
:param text: (string) the content of the mail
:param recipient: (string) the recipient of the mail
:param subject: (string) the subject of the mail
2018-01-05 10:20:07 +00:00
:param attachment: (string) the path to the logfile
2018-01-01 10:23:50 +00:00
:return: string for logging purposes, contains recipient & subject
"""
2018-01-05 10:20:07 +00:00
msg = MIMEMultipart()
msg.attach(MIMEText(text))
2018-01-01 10:23:50 +00:00
msg["From"] = self.fromaddr
msg["To"] = recipient
msg["Subject"] = subject
2018-01-05 10:20:07 +00:00
# attach logfile
if attachment:
with open(attachment, "rb") as fil:
part = MIMEApplication(
fil.read(),
Name="logfile"
)
# After the file is closed
part['Content-Disposition'] = 'attachment; filename="logfile"'
msg.attach(part)
2018-01-01 10:23:50 +00:00
self.s.send_message(msg)
2018-01-05 10:20:07 +00:00
self.s.close()
2018-01-01 10:23:50 +00:00
return "Sent mail to " + recipient + ": " + subject
def sendmail(to, subject, city=None, body=''):
msg = MIMEMultipart()
if city:
msg['From'] = 'Ticketfrei <%s@%s>' % (city, getfqdn())
else:
msg['From'] = 'Ticketfrei <%s@%s>' % (getuser(), getfqdn())
msg['To'] = to
2018-03-29 00:40:22 +00:00
msg['Subject'] = '[Ticketfrei] %s' % (subject, )
msg.attach(MIMEText(body))
with smtplib.SMTP('localhost') as smtp:
smtp.send_message(msg)
2018-01-01 10:23:50 +00:00
# For testing:
if __name__ == '__main__':
2018-03-28 18:24:21 +00:00
m = Mailer()
print(m.send("This is a test mail.", m.fromaddr, "Test"))