Class to handle email configuration and sending functionality
Source code in dashboard/send_mail.py
class EmailSender:
"""Class to handle email configuration and sending functionality"""
def __init__(self, smtp_config_path: Path, smtp_host: str = '127.0.0.1', smtp_port: int = 25):
# def __init__(self, smtp_config_path: Path, smtp_host: str = 'pro2.mail.ovh.net', smtp_port: int = 587):
"""
Initialize EmailSender with configuration file path and SMTP settings.
Args:
config_path (str | Path): Path to YAML configuration file
smtp_host (str, optional): SMTP server host. Defaults to '127.0.0.1'
smtp_port (int, optional): SMTP server port. Defaults to 25
"""
self.config_path = smtp_config_path
self.smtp_host = smtp_host
self.smtp_port = smtp_port
self.config = self._load_config()
def _load_config(self) -> Dict[str, Any]:
"""
Load and validate SMTP configuration from YAML file.
Returns:
Dict[str, Any]: Dictionary containing the SMTP configuration
Raises:
FileNotFoundError: If the configuration file doesn't exist
yaml.YAMLError: If the YAML file is invalid
KeyError: If required configuration keys are missing
"""
try:
logger.info(f"Loading SMTP configuration from {self.config_path}")
if not self.config_path.exists():
logger.error(f"Configuration file not found: {self.config_path}")
raise FileNotFoundError(f"Configuration file not found: {self.config_path}")
with open(self.config_path, 'r', encoding='utf-8') as file:
config = yaml.safe_load(file)
# Validate required configuration keys
required_keys = {'EMAIL_ADDRESS', 'RECIPIENTS', 'ATTACHEMENTS'}
if not all(key in config.get('SMTP_CONFIG', {}) for key in required_keys):
missing_keys = required_keys - set(config.get('SMTP_CONFIG', {}).keys())
logger.error(f"Missing required configuration keys: {missing_keys}")
raise KeyError(f"Missing required configuration keys: {missing_keys}")
logger.success("SMTP configuration loaded successfully")
return config['SMTP_CONFIG']
except yaml.YAMLError as e:
logger.error(f"Error parsing YAML file: {str(e)}")
raise
except Exception as e:
logger.error(f"Unexpected error while loading configuration: {str(e)}")
raise
def send(
self,
subject: str,
body: str,
file_date: str,
diffusion_path: str = './diffusion'
) -> bool:
"""
Send an email with attachments using SMTP
Args:
subject (str): Email subject
body (str): Email body content
file_date (str): Date to prefix attachment filenames
cc_recipients (List[str], optional): List of CC recipients
diffusion_path (str, optional): Path to attachment files
Returns:
bool: True if email sent successfully, False otherwise
Raises:
smtplib.SMTPAuthenticationError: If authentication fails
smtplib.SMTPException: If SMTP error occurs
FileNotFoundError: If attachment file is not found
"""
try:
logger.info("Creating email message")
msg = EmailMessage()
msg['Subject'] = subject
msg['From'] = self.config['EMAIL_ADDRESS']
msg['To'] = ",".join(self.config['RECIPIENTS'])
if self.config['Cc']:
msg['Cc'] = ",".join(self.config['Cc'])
msg.set_content(body)
# Add attachments
for file in self.config['ATTACHEMENTS']:
filename = f"{file_date}_{file}" if file != 'qualité_données.txt' else file
file_path = diffusion_dir / filename
try:
ctype, encoding = mimetypes.guess_type(str(file_path))
if ctype is None or encoding is not None:
ctype = 'application/octet-stream'
maintype, subtype = ctype.split('/', 1)
with open(file_path, 'rb') as fp:
msg.add_attachment(
fp.read(),
maintype=maintype,
subtype=subtype,
filename=filename
)
logger.info(f"Added attachment: {filename}")
except FileNotFoundError:
logger.error(f"Attachment file not found: {file_path}")
raise
# Send the email
logger.info("Establishing SMTP connection")
# context = ssl.create_default_context()
with smtplib.SMTP(host=self.smtp_host, port=self.smtp_port) as smtp:
# smtp.starttls(context=context)
email_password = os.environ.get('MAIL_PWD')
# smtp.login(self.config['EMAIL_ADDRESS'], email_password)
smtp.send_message(msg)
logger.success("Email sent successfully")
return True
except smtplib.SMTPAuthenticationError:
logger.error("SMTP authentication failed")
raise
except smtplib.SMTPException as e:
logger.error(f"SMTP error occurred: {str(e)}")
raise
except Exception as e:
logger.error(f"Unexpected error occurred: {str(e)}")
raise
Functions
__init__(smtp_config_path, smtp_host='127.0.0.1', smtp_port=25)
Initialize EmailSender with configuration file path and SMTP settings.
| Parameters: |
-
config_path
(str | Path)
–
Path to YAML configuration file
-
smtp_host
(str, default:
'127.0.0.1'
)
–
SMTP server host. Defaults to '127.0.0.1'
-
smtp_port
(int, default:
25
)
–
SMTP server port. Defaults to 25
|
Source code in dashboard/send_mail.py
def __init__(self, smtp_config_path: Path, smtp_host: str = '127.0.0.1', smtp_port: int = 25):
# def __init__(self, smtp_config_path: Path, smtp_host: str = 'pro2.mail.ovh.net', smtp_port: int = 587):
"""
Initialize EmailSender with configuration file path and SMTP settings.
Args:
config_path (str | Path): Path to YAML configuration file
smtp_host (str, optional): SMTP server host. Defaults to '127.0.0.1'
smtp_port (int, optional): SMTP server port. Defaults to 25
"""
self.config_path = smtp_config_path
self.smtp_host = smtp_host
self.smtp_port = smtp_port
self.config = self._load_config()
send(subject, body, file_date, diffusion_path='./diffusion')
Send an email with attachments using SMTP
| Parameters: |
-
subject
(str)
–
-
body
(str)
–
-
file_date
(str)
–
Date to prefix attachment filenames
-
cc_recipients
(List[str])
–
-
diffusion_path
(str, default:
'./diffusion'
)
–
|
| Returns: |
-
bool( bool
) –
True if email sent successfully, False otherwise
|
| Raises: |
-
SMTPAuthenticationError
–
-
SMTPException
–
-
FileNotFoundError
–
If attachment file is not found
|
Source code in dashboard/send_mail.py
def send(
self,
subject: str,
body: str,
file_date: str,
diffusion_path: str = './diffusion'
) -> bool:
"""
Send an email with attachments using SMTP
Args:
subject (str): Email subject
body (str): Email body content
file_date (str): Date to prefix attachment filenames
cc_recipients (List[str], optional): List of CC recipients
diffusion_path (str, optional): Path to attachment files
Returns:
bool: True if email sent successfully, False otherwise
Raises:
smtplib.SMTPAuthenticationError: If authentication fails
smtplib.SMTPException: If SMTP error occurs
FileNotFoundError: If attachment file is not found
"""
try:
logger.info("Creating email message")
msg = EmailMessage()
msg['Subject'] = subject
msg['From'] = self.config['EMAIL_ADDRESS']
msg['To'] = ",".join(self.config['RECIPIENTS'])
if self.config['Cc']:
msg['Cc'] = ",".join(self.config['Cc'])
msg.set_content(body)
# Add attachments
for file in self.config['ATTACHEMENTS']:
filename = f"{file_date}_{file}" if file != 'qualité_données.txt' else file
file_path = diffusion_dir / filename
try:
ctype, encoding = mimetypes.guess_type(str(file_path))
if ctype is None or encoding is not None:
ctype = 'application/octet-stream'
maintype, subtype = ctype.split('/', 1)
with open(file_path, 'rb') as fp:
msg.add_attachment(
fp.read(),
maintype=maintype,
subtype=subtype,
filename=filename
)
logger.info(f"Added attachment: {filename}")
except FileNotFoundError:
logger.error(f"Attachment file not found: {file_path}")
raise
# Send the email
logger.info("Establishing SMTP connection")
# context = ssl.create_default_context()
with smtplib.SMTP(host=self.smtp_host, port=self.smtp_port) as smtp:
# smtp.starttls(context=context)
email_password = os.environ.get('MAIL_PWD')
# smtp.login(self.config['EMAIL_ADDRESS'], email_password)
smtp.send_message(msg)
logger.success("Email sent successfully")
return True
except smtplib.SMTPAuthenticationError:
logger.error("SMTP authentication failed")
raise
except smtplib.SMTPException as e:
logger.error(f"SMTP error occurred: {str(e)}")
raise
except Exception as e:
logger.error(f"Unexpected error occurred: {str(e)}")
raise