sending mails using SMTP
This commit is contained in:
Binary file not shown.
Binary file not shown.
@@ -1,13 +1,90 @@
|
||||
from flask import request
|
||||
from models import Notif, NotifType, db, EmailTemplate, Mail
|
||||
from models import Notif, NotifType, db, EmailTemplate, Mail, KeyValueSettings
|
||||
from typing import Optional, Dict, Any, List
|
||||
from datetime import datetime, timedelta
|
||||
from flask_login import current_user
|
||||
from sqlalchemy import desc
|
||||
import logging
|
||||
import smtplib
|
||||
from email.mime.text import MIMEText
|
||||
from email.mime.multipart import MIMEMultipart
|
||||
import json
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
def get_smtp_settings() -> Optional[Dict[str, Any]]:
|
||||
"""
|
||||
Get SMTP settings from the database.
|
||||
|
||||
Returns:
|
||||
Dictionary containing SMTP settings or None if not configured
|
||||
"""
|
||||
try:
|
||||
smtp_settings = KeyValueSettings.get_value('smtp_settings')
|
||||
if not smtp_settings:
|
||||
logger.warning("No SMTP settings found in database")
|
||||
return None
|
||||
return smtp_settings
|
||||
except Exception as e:
|
||||
logger.error(f"Error retrieving SMTP settings: {str(e)}")
|
||||
return None
|
||||
|
||||
def send_email_via_smtp(mail: Mail) -> bool:
|
||||
"""
|
||||
Send an email using the configured SMTP settings.
|
||||
|
||||
Args:
|
||||
mail: The Mail object containing the email details
|
||||
|
||||
Returns:
|
||||
bool: True if email was sent successfully, False otherwise
|
||||
"""
|
||||
smtp_settings = get_smtp_settings()
|
||||
if not smtp_settings:
|
||||
logger.error("Cannot send email: SMTP settings not configured")
|
||||
return False
|
||||
|
||||
try:
|
||||
# Create message
|
||||
msg = MIMEMultipart()
|
||||
msg['From'] = f"{smtp_settings['smtp_from_name']} <{smtp_settings['smtp_from_email']}>"
|
||||
msg['To'] = mail.recipient
|
||||
msg['Subject'] = mail.subject
|
||||
|
||||
# Attach HTML body
|
||||
msg.attach(MIMEText(mail.body, 'html'))
|
||||
|
||||
# Create SMTP connection
|
||||
if smtp_settings['smtp_security'] == 'ssl':
|
||||
server = smtplib.SMTP_SSL(smtp_settings['smtp_host'], int(smtp_settings['smtp_port']))
|
||||
else:
|
||||
server = smtplib.SMTP(smtp_settings['smtp_host'], int(smtp_settings['smtp_port']))
|
||||
if smtp_settings['smtp_security'] == 'tls':
|
||||
server.starttls()
|
||||
|
||||
# Login if credentials are provided
|
||||
if smtp_settings['smtp_username'] and smtp_settings['smtp_password']:
|
||||
server.login(smtp_settings['smtp_username'], smtp_settings['smtp_password'])
|
||||
|
||||
# Send email
|
||||
server.send_message(msg)
|
||||
server.quit()
|
||||
|
||||
# Update mail status
|
||||
mail.status = 'sent'
|
||||
mail.sent_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
|
||||
logger.info(f"Email sent successfully to {mail.recipient}")
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error sending email: {str(e)}")
|
||||
mail.status = 'failed'
|
||||
mail.error_message = str(e)
|
||||
db.session.commit()
|
||||
return False
|
||||
|
||||
def generate_mail_from_notification(notif: Notif) -> Optional[Mail]:
|
||||
"""
|
||||
Generate a mail record from a notification using the appropriate email template.
|
||||
@@ -98,7 +175,13 @@ def generate_mail_from_notification(notif: Notif) -> Optional[Mail]:
|
||||
notif_id=notif.id
|
||||
)
|
||||
db.session.add(mail)
|
||||
logger.debug(f"Created mail record: {mail}")
|
||||
|
||||
# Try to send the email immediately
|
||||
if send_email_via_smtp(mail):
|
||||
logger.debug(f"Email sent successfully for notification: {notif}")
|
||||
else:
|
||||
logger.warning(f"Failed to send email for notification: {notif}")
|
||||
|
||||
return mail
|
||||
except Exception as e:
|
||||
logger.error(f"Error generating mail from notification: {str(e)}")
|
||||
|
||||
Reference in New Issue
Block a user