fixing #44 - refactoring how mails are sent

multi-deployment
b3yond 2018-10-06 10:20:37 +02:00
parent 4851fc0b63
commit 2068b99b87
3 changed files with 5 additions and 65 deletions

View File

@ -1,7 +1,7 @@
#!/usr/bin/env python3
import logging
import sendmail
from sendmail import sendmail
import datetime
import mailbox
import email
@ -37,7 +37,7 @@ class Mailbot(Bot):
if report.author != rec:
try:
city = user.get_city()
sendmail.sendmail(rec, "Ticketfrei " + city + " Report",
sendmail(rec, "Ticketfrei " + city + " Report",
city=city, body=body)
except Exception:
logger.error("Sending Mail failed.", exc_info=True)

2
db.py
View File

@ -1,7 +1,7 @@
from config import config
import jwt
import logging
from os import urandom, system
from os import urandom
from pylibscrypt import scrypt_mcf
import sqlite3

View File

@ -1,76 +1,16 @@
#!/usr/bin/env python3
from config import config
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
import logging
from getpass import getuser
import smtplib
from socket import getfqdn
import ssl
logger = logging.getLogger(__name__)
class Mailer(object):
"""
Maintains the connection to the mailserver and sends text to users.
"""
def __init__(self):
"""
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.
"""
# 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]
# starts a client session with the SMTP server
self.s = smtplib.SMTP(config["mail"]["mailserver"])
try:
context = ssl.create_default_context()
self.s.starttls(context=context)
except BaseException: # TODO: Amend specific exception
logger.error('StartTLS failed.', exc_info=True)
self.s.login(config["mail"]["user"], config["mail"]["passphrase"])
def send(self, text, recipient, subject, attachment=None):
"""
:param text: (string) the content of the mail
:param recipient: (string) the recipient of the mail
:param subject: (string) the subject of the mail
:param attachment: (string) the path to the logfile
:return: string for logging purposes, contains recipient & subject
"""
msg = MIMEMultipart()
msg.attach(MIMEText(text))
msg["From"] = self.fromaddr
msg["To"] = recipient
msg["Subject"] = subject
# 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)
self.s.send_message(msg)
self.s.close()
return "Sent mail to " + recipient + ": " + subject
def sendmail(to, subject, city=None, body=''):
msg = MIMEMultipart()
if city:
@ -87,5 +27,5 @@ def sendmail(to, subject, city=None, body=''):
# For testing:
if __name__ == '__main__':
m = Mailer()
print(m.send("This is a test mail.", m.fromaddr, "Test"))
sendmail(config['mail']['contact'], "Test Mail",
body="This is a test mail.")