41 lines
1.4 KiB
Python
41 lines
1.4 KiB
Python
import smtplib
|
|
from email.mime.text import MIMEText
|
|
from email.mime.multipart import MIMEMultipart
|
|
import os
|
|
from dotenv import load_dotenv
|
|
|
|
load_dotenv()
|
|
|
|
class EmailService:
|
|
SMTP_HOST = os.getenv("SMTP_HOST")
|
|
SMTP_PORT = int(os.getenv("SMTP_PORT", 465))
|
|
SMTP_USER = os.getenv("SMTP_USER")
|
|
SMTP_PASSWORD = os.getenv("SMTP_PASSWORD")
|
|
EMAIL_FROM = os.getenv("EMAIL_FROM")
|
|
SMTP_SECURE = os.getenv("SMTP_SECURE", "true").lower() == "true"
|
|
|
|
@staticmethod
|
|
def send_otp(to_email: str, otp: str):
|
|
try:
|
|
msg = MIMEMultipart()
|
|
msg['From'] = EmailService.EMAIL_FROM
|
|
msg['To'] = to_email
|
|
msg['Subject'] = "Password Reset OTP"
|
|
|
|
body = f"Your OTP for password reset is: {otp}. It expires in 10 minutes."
|
|
msg.attach(MIMEText(body, 'plain'))
|
|
|
|
if EmailService.SMTP_SECURE:
|
|
server = smtplib.SMTP_SSL(EmailService.SMTP_HOST, EmailService.SMTP_PORT)
|
|
else:
|
|
server = smtplib.SMTP(EmailService.SMTP_HOST, EmailService.SMTP_PORT)
|
|
server.starttls()
|
|
|
|
server.login(EmailService.SMTP_USER, EmailService.SMTP_PASSWORD)
|
|
text = msg.as_string()
|
|
server.sendmail(EmailService.EMAIL_FROM, to_email, text)
|
|
server.quit()
|
|
return True
|
|
except Exception as e:
|
|
print(f"Failed to send email: {e}")
|
|
return False |