first commit
This commit is contained in:
77
src/email/sender.py
Normal file
77
src/email/sender.py
Normal file
@@ -0,0 +1,77 @@
|
||||
"""Email sending via SMTP"""
|
||||
|
||||
import smtplib
|
||||
from email.mime.text import MIMEText
|
||||
from email.mime.multipart import MIMEMultipart
|
||||
from email.utils import formatdate
|
||||
|
||||
from ..config import get_config
|
||||
from ..logger import get_logger
|
||||
|
||||
logger = get_logger()
|
||||
|
||||
|
||||
class EmailSender:
|
||||
"""Send emails via SMTP"""
|
||||
|
||||
def __init__(self):
|
||||
config = get_config()
|
||||
self.config = config.email
|
||||
|
||||
def send(self, subject: str, html_content: str, text_content: str) -> bool:
|
||||
"""
|
||||
Send email with HTML and plain text versions
|
||||
|
||||
Args:
|
||||
subject: Email subject line
|
||||
html_content: HTML email body
|
||||
text_content: Plain text email body
|
||||
|
||||
Returns:
|
||||
True if sent successfully, False otherwise
|
||||
"""
|
||||
try:
|
||||
# Create message
|
||||
msg = MIMEMultipart("alternative")
|
||||
msg["Subject"] = subject
|
||||
msg["From"] = f"{self.config.from_name} <{self.config.from_}>"
|
||||
msg["To"] = self.config.to
|
||||
msg["Date"] = formatdate(localtime=True)
|
||||
|
||||
# Attach parts
|
||||
part_text = MIMEText(text_content, "plain", "utf-8")
|
||||
part_html = MIMEText(html_content, "html", "utf-8")
|
||||
|
||||
msg.attach(part_text)
|
||||
msg.attach(part_html)
|
||||
|
||||
# Send via SMTP
|
||||
smtp_config = self.config.smtp
|
||||
|
||||
if smtp_config.use_ssl:
|
||||
server = smtplib.SMTP_SSL(smtp_config.host, smtp_config.port)
|
||||
else:
|
||||
server = smtplib.SMTP(smtp_config.host, smtp_config.port)
|
||||
|
||||
try:
|
||||
if smtp_config.use_tls and not smtp_config.use_ssl:
|
||||
server.starttls()
|
||||
|
||||
# Login if credentials provided
|
||||
if smtp_config.username and smtp_config.password:
|
||||
server.login(smtp_config.username, smtp_config.password)
|
||||
|
||||
# Send email
|
||||
server.send_message(msg)
|
||||
logger.info(f"Email sent successfully to {self.config.to}")
|
||||
return True
|
||||
|
||||
finally:
|
||||
server.quit()
|
||||
|
||||
except smtplib.SMTPException as e:
|
||||
logger.error(f"SMTP error sending email: {e}")
|
||||
return False
|
||||
except Exception as e:
|
||||
logger.error(f"Unexpected error sending email: {e}")
|
||||
return False
|
||||
Reference in New Issue
Block a user