import smtplib from datetime import datetime from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.header import Header from . import LOGGER class EmailController(): def __init__(self, smtpServer, user, passwd, port = 587, email = ""): self.smtpServer = smtpServer self.port = port self.user = user self.passwd = passwd if email: self.email = email else: self.email = user def __connect__(self): self.smtp = smtplib.SMTP(self.smtpServer, self.port) self.smtp.starttls() self.smtp.login(self.user, self.passwd) def sendMail(self, user): try: if user.mail == 'None' or not user.mail: LOGGER.debug("cant send email to {}. Has no email-address. {}".format(user.uid, {'error': True, 'user': {'userId': user.uid, 'firstname': user.firstname, 'lastname': user.lastname}})) raise Exception("no valid Email") msg = MIMEMultipart() msg['From'] = self.email msg['To'] = user.mail msg['Subject'] = Header('Gerücht, bezahle deine Schulden!', 'utf-8') sum = user.getGeruecht(datetime.now().year).getSchulden() if sum < 0: type = 'Schulden' add = 'Bezahle diese umgehend an den Finanzer.' else: type = 'Guthaben' add = '' text = MIMEText("Hallo {} {},\nDu hast {} im Wert von {:.2f} €. {}\n\nDiese Nachricht wurde automatisch erstellt.".format(user.firstname, user.lastname, type, abs(sum)/100, add), 'plain', 'utf-8') msg.attach(text) LOGGER.debug("Send email to {}: '{}'".format(user.uid, msg.as_string())) self.__connect__() self.smtp.sendmail(self.email, user.mail, msg.as_string()) LOGGER.debug("Sended email to {}. {}".format(user.uid, {'error': False, 'user': {'userId': user.uid, 'firstname': user.firstname, 'lastname': user.lastname}})) return {'error': False, 'user': {'userId': user.uid, 'firstname': user.firstname, 'lastname': user.lastname}} except Exception: return {'error': True, 'user': {'userId': user.uid, 'firstname': user.firstname, 'lastname': user.lastname}}