Python3 Outlook SMPT Email Example using SMTPLIB
Populate Ecrypted Constants from Environment Variables Code and Cryptography


import os
import smtplib
from email.message import EmailMessage
from cryptography.fernet import Fernet
from dotenv import load_dotenv

# Load environment variables from the .env file
def initialize():
    load_dotenv()

    # Get the decryption key and encrypted password from environment variables
    DECRYPTION_KEY = bytes(os.getenv("DECRYPTION_KEY"), encoding='utf-8')
    ENCRYPTED_PASSWORD = bytes(os.getenv("ENCRYPTED_PASSWORD"), encoding='utf-8')

    # Initialize the Fernet cipher suite with the decryption key
    cipher_suite = Fernet(DECRYPTION_KEY)
    # Decrypt the encrypted password
    decrypted_password = cipher_suite.decrypt(ENCRYPTED_PASSWORD).decode()
    # Get the email sender from environment variables
    email_sender = os.getenv("EMAIL_SENDER")

    return email_sender, decrypted_password

# Main function to send an email
def main():
    # Initialize email sender and decrypted password
    email_sender, decrypted_password = initialize()

    # Define the email recipient
    email_recipient = "john.doe@example.com"

    # Define the HTML email message
    email_message = """
    <html>
        <body>
            <h1>Hello world!</h1>
            <p>This is a test email sent from Python.</p>
            <p>Regards,</p>
            <p>Python Learner</p>
        </body>
    </html>
    """
    email = EmailMessage()
    # Set the email sender
    email["From"] = email_sender
    # Set the email recipient
    email["To"] = email_recipient
    # Set the email subject
    email["Subject"] = "Test Email 4"

    # Set the content type to "text/html"
    email.add_alternative(email_message, subtype='html')

    # Connect to the SMTP server
    email_smtp = smtplib.SMTP("smtp-mail.outlook.com", port=587)
    # Start TLS encryption
    email_smtp.starttls()
    # Login to the email server using the sender's email and decrypted password
    email_smtp.login(email_sender, decrypted_password)
    # Send the email
    email_smtp.sendmail(email_sender, email_recipient, email.as_string())
    # Quit the SMTP server
    email_smtp.quit()

if __name__ == "__main__":
    main()


.env Environment Variables File

# .env
DECRYPTION_KEY="G5YLK1KdKpQZjT5p30Chd9SJ2KVc9e_7qeQ1EDufPHU="
ENCRYPTED_PASSWORD="gAAAAABkw6rzPNKDivFJgvBMkY_07i2MI0ZOmXMw-oJgTPXzLS8p7SmJ6O7uDiL652s8AjHc5kEoL6KX3Wy-gp4cSgfdsted3g=="
EMAIL_SENDER="jane.doe@example.com