Skip to content

Email Sender Module

EmailSender

dadosfera.services.email_sender.email_sender.EmailSender

EmailSender(smtp_server, port, from_email, password, use_ssl=False)

Initializes the EmailSender class.

PARAMETER DESCRIPTION
smtp_server

SMTP server.

TYPE: str

port

SMTP server port.

TYPE: int

from_email

Sender's email.

TYPE: str

app_password

APP password to SMTP authenticate.

TYPE: str

Source code in dadosfera/services/email_sender/email_sender.py
30
31
32
33
34
35
36
37
38
39
def __init__(self, smtp_server, port, from_email, password, use_ssl=False):
    self.smtp_server = smtp_server
    self.port = port
    self.from_email = from_email
    self.app_password = password
    self.use_ssl = use_ssl

    # Validate parameters to avoid runtime errors
    if not all([smtp_server, port, from_email, password]):
        raise ValueError("Please provide all parameters, they are mandatory.")

create_message

create_message(to_email, subject, body, mimetype=PLAIN, attachment_path=None)

Creates an email message.

PARAMETER DESCRIPTION
to_email

Recipient's email(s).

TYPE: str or list

subject

Email subject.

TYPE: str

body

Email message body content.

TYPE: str

mimetype

Email message body content type (default 'plain').

TYPE: str DEFAULT: PLAIN

attachment_path

Path to the attachment file.

TYPE: str DEFAULT: None

Returns: MIMEMultipart: Email message created.

Source code in dadosfera/services/email_sender/email_sender.py
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
def create_message(self, to_email, subject, body, mimetype=MessageMimeType.PLAIN, attachment_path=None):
    """
    Creates an email message.

    Parameters:
        to_email (str or list): Recipient's email(s).
        subject (str): Email subject.
        body (str): Email message body content.
        mimetype (str): Email message body content type (default 'plain').
        attachment_path (str): Path to the attachment file.
    Returns:
        MIMEMultipart: Email message created.
    """
    if isinstance(to_email, str):
        to_email = [to_email]

    message = MIMEMultipart()
    message["From"] = self.from_email
    message["To"] = ', '.join(to_email)
    message["Subject"] = subject
    message.attach(MIMEText(body, mimetype.value))

    if attachment_path:
        self.attach_file(message, attachment_path)

    return message

attach_file

attach_file(msg, attachment_path)

Attaches a file to the email message.

PARAMETER DESCRIPTION
msg

Email message.

TYPE: MIMEMultipart

attachment_path

Path to the attachment file.

TYPE: str

Source code in dadosfera/services/email_sender/email_sender.py
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
def attach_file(self, msg, attachment_path):
    """
    Attaches a file to the email message.

    Parameters:
        msg (MIMEMultipart): Email message.
        attachment_path (str): Path to the attachment file.
    """
    if attachment_path and os.path.isfile(attachment_path):
        try:
            # Guess the MIME type of the attachment file based on its extension
            mime_type, _ = mimetypes.guess_type(attachment_path)
            if mime_type is None:
                mime_type = "application/octet-stream" # Default MIME type

            # Split the MIME type into main and sub types
            main_type, sub_type = mime_type.split("/", 1)

            with open(attachment_path, "rb") as attachment:
                part = MIMEBase(main_type, sub_type)
                part.set_payload(attachment.read())
                encoders.encode_base64(part)
                part.add_header(
                    "Content-Disposition",
                    f'attachment; filename= "{os.path.basename(attachment_path)}"'
                )
                msg.attach(part)
        except Exception as e:
            logger.error(f"Error attaching file: {e}")
            raise e
    else:
        logger.error(f"Attachment file not found: {attachment_path}")
        raise FileNotFoundError(f"Attachment file not found: {attachment_path}")

send_email

send_email(to_email, message)

Sends an email message using SMTP server.

PARAMETER DESCRIPTION
to_email

Recipient's email(s).

TYPE: str or list

message

Email message.

TYPE: MIMEMultipart

Source code in dadosfera/services/email_sender/email_sender.py
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
def send_email(self, to_email, message):
    """
    Sends an email message using SMTP server.

    Parameters:
        to_email (str or list): Recipient's email(s).
        message (MIMEMultipart): Email message.
    """
    try:
        server = smtplib.SMTP(self.smtp_server, self.port)
        if self.use_ssl:
            server.starttls()

        server.login(self.from_email, self.app_password)
        server.sendmail(self.from_email, to_email, message.as_string())
        logger.info(f"Email(s) sent successfully!")
    except Exception as e:
        logger.error(f"An error occurred: {e}")
    finally:
        server.quit()