pywallter/tools/mailer.py

66 lines
2.1 KiB
Python

from flask import Flask
import os, smtplib, ssl
from email.message import EmailMessage
app = Flask( 'pywallter' )
app.config.from_pyfile('config.py')
class Mailer:
def __init__(self):
self._smtp_server = app.config['SMTP_SERVER']
self._smtp_port = app.config['SMTP_PORT']
self._smtp_user = app.config['SMTP_USER']
self._smtp_passwd = app.config['SMTP_PASSWD']
self._sender_address = app.config['SENDER_ADDRESS']
def get_smtp_conf(self):
print ("Serveur SMTP: _smtp_server")
return self._smtp_server
def send_email(self, receiver_email, subject, message):
mail = EmailMessage()
mail['Subject'] = subject
mail['From'] = self._sender_address
mail['To'] = receiver_email
mail.set_content(message)
match self._smtp_port:
case "465":
self._send_ssl_mail(receiver_email, mail)
case "587":
self._send_starttls_mail(receiver_email, mail)
case "25":
with smtplib.SMTP(self._smtp_server, self._smtp_port) as server:
server.login(self._smtp_user, self._smtp_password)
server.sendmail(self._sender_address, receiver_email, mail.as_string())
case _:
print ("There are problem with mail port configuration ")
def _send_starttls_mail(self, receiver_email, mail):
context = ssl.create_default_context()
with smtplib.SMTP(self._smtp_server, self._smtp_port) as server:
server.ehlo() # Can be omitted
server.starttls(context=context)
server.ehlo() # Can be omitted
server.login(self._smtp_user, self._smtp_passwd)
server.sendmail(self._sender_address, receiver_email, mail.as_string())
def _send_ssl_mail(receiver_email, mail):
context = ssl.create_default_context()
with smtplib.SMTP(self._smtp_server, self._smtp_port) as server:
server.login(sender_email, password)
server.sendmail(self._sender_address, receiver_email, mail.as_string())