Send Mail

dashboard.send_mail

Classes

EmailSender

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) –

    Email subject

  • body (str) –

    Email body content

  • file_date (str) –

    Date to prefix attachment filenames

  • cc_recipients (List[str]) –

    List of CC recipients

  • diffusion_path (str, default: './diffusion' ) –

    Path to attachment files

Returns:
  • bool( bool ) –

    True if email sent successfully, False otherwise

Raises:
  • SMTPAuthenticationError –

    If authentication fails

  • SMTPException –

    If SMTP error occurs

  • 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

Functions

send_mail(env, date, smtp_host)

Point d'entrée principal pour l'envoi d'un email avec les détails du rapport de tension hospitalière.

Cette fonction initialise un gestionnaire de date, crée une instance d'EmailSender avec la configuration définie dans le fichier YAML, et envoie un email contenant des livrables basés sur la date fournie.

Parameters:
  • env (str) –

    L'environnement pour lequel l'email doit être envoyé.

  • date (str) –

    La date pour laquelle les informations doivent être incorporées dans l'email, au format 'YYYY-MM-DD'.

Returns:
  • None( None ) –

    La fonction ne retourne pas de valeur, mais envoie un email sur la base des paramètres fournis.

Raises:
  • Exception –

    Pour toute exception qui pourrait se produire lors de l'initialisation de l'EmailSender ou lors de l'envoi de l'email.

Notes
  • Assurez-vous que l'environnement et la date sont corrects pour éviter toute confusion dans les livrables envoyés.
  • Le mot de passe de l'email doit être stocké dans l'environnement sous la clé "MAIL_PWD".

Exemple d'utilisation: main(env="production", date="2023-10-01")

Source code in dashboard/send_mail.py
def send_mail(env:str, date:str, smtp_host:str) -> None:
    """
    Point d'entrée principal pour l'envoi d'un email avec les détails du rapport de tension hospitalière.

    Cette fonction initialise un gestionnaire de date, crée une instance d'EmailSender avec la 
    configuration définie dans le fichier YAML, et envoie un email contenant des livrables 
    basés sur la date fournie.

    Args:
        env (str): L'environnement pour lequel l'email doit être envoyé.
        date (str): La date pour laquelle les informations doivent être incorporées dans l'email, 
                    au format 'YYYY-MM-DD'.

    Returns:
        None: La fonction ne retourne pas de valeur, mais envoie un email sur la base des 
              paramètres fournis.

    Raises:
        Exception: Pour toute exception qui pourrait se produire lors de l'initialisation 
                   de l'EmailSender ou lors de l'envoi de l'email.

    Notes:
        - Assurez-vous que l'environnement et la date sont corrects pour éviter toute 
          confusion dans les livrables envoyés.
        - Le mot de passe de l'email doit être stocké dans l'environnement sous la clé 
          "MAIL_PWD".

    Exemple d'utilisation:
        main(env="production", date="2023-10-01")
    """

    dt = DateTimeManager(date)
    file_date = dt.file_date
    # Initialize email sender with configuration
    email_sender = EmailSender(smtp_config_path, smtp_host = smtp_host)

    # Send email
    email_sender.send(
        subject='TDB Tension Hospitalière [Recette]',
        body="Bonjour, \n\nCeci est un mail de recette pour les TDB ROR national.\nMerci de ne pas en prendre compte.\n\nCordialement",
        file_date=file_date,  # Replace with actual date
    )