Skip to content

Commit

Permalink
fix(backend): emails sending
Browse files Browse the repository at this point in the history
  • Loading branch information
EliotAmn committed Feb 3, 2025
1 parent c09e4e9 commit 4156b7c
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 29 deletions.
44 changes: 19 additions & 25 deletions app/services/mail_service.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
import os
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

from mailersend import emails

import yagmail
from app.tools.teklogger import log_debug, log_error, log_info, log_success
import smtplib


class MailService:
Expand All @@ -19,29 +22,20 @@ def send_mail(recipient: str, subject: str, body: str):
log_info(f"Sending mail to {recipient}")

try:
mailer = emails.NewEmail(os.getenv("MAILERSEND_API_KEY"))

mail_body = {}

mail_from = {
"name": "TekBetter Dashboard",
"email": os.getenv("MAILERSEND_FROM_EMAIL"),
}

recipients = [
{
"email": recipient,
}
]

mailer.set_mail_from(mail_from, mail_body)
mailer.set_mail_to(recipients, mail_body)
mailer.set_subject(subject, mail_body)
mailer.set_plaintext_content(body, mail_body)

response = mailer.send(mail_body)
log_debug(response)
smtp_server = os.getenv('SMTP_SERVER')
smtp_port = int(os.getenv('SMTP_PORT'))
smtp_user = os.getenv('SMTP_USER')
smtp_password = os.getenv('SMTP_PASSWORD')
yag = yagmail.SMTP(user=smtp_user, password=smtp_password, host=smtp_server, port=smtp_port)
html_content = f"""
<html>
<body>
<h2>{subject}</h2>
<p>{body}</p>
</body>
</html>
"""
yag.send(to=recipient, subject=subject, contents=html_content)
log_success(f"Mail sent to {recipient}")

except Exception as e:
log_error(f"Failed to send mail to {recipient}: {e}")
log_error(f"Failed to send mail to {recipient}: {e}")
4 changes: 1 addition & 3 deletions app/tools/envloader.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,6 @@
"AES_KEY": None,
"DATA_PATH": "./data",
"ENABLE_MAILER": "false",
"MAILERSEND_API_KEY": "",
"MAILERSEND_FROM_EMAIL": ""
}


Expand All @@ -44,7 +42,7 @@ def load_env():
log_debug("Loading environment variables")
load_dotenv()

smtp_vars = ["MAILERSEND_API_KEY", "MAILERSEND_FROM_EMAIL"]
smtp_vars = ["SMTP_SERVER", "SMTP_PORT", "SMTP_USER", "SMTP_PASSWORD"]
if os.getenv("ENABLE_MAILER") == "true":
for var in smtp_vars:
if os.getenv(var) is None:
Expand Down
4 changes: 3 additions & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -36,4 +36,6 @@ wsproto~=1.2.0
webdriver-manager~=4.0.2
PyJWT~=2.10.1
ics~=0.7.2
mailersend~=0.5.8
mailersend~=0.5.8
jwt~=1.3.1
yagmail~=0.15.293

0 comments on commit 4156b7c

Please sign in to comment.