r/PythonLearning • • Feb 27 '25

Send mail with Python easily

Post image
189 Upvotes

15 comments sorted by

View all comments

10

u/FoolsSeldom Feb 27 '25

Did you have a question? Or are you just showing people a technique? (If the latter, why not share the code, rather than a screen shot?)

11

u/RunPython Feb 27 '25

So sorry.
I want to share the code structure.

Here is the total code.
Thanks.

import smtplib
import ssl
from email.message import EmailMessage


def email(toMails):
    # Define email sender and receiver
    email_sender = "[email protected]" # Your Mail
    app_password = "get app password here" # Get Google App Password from your mail
    
    # to get app_password visit and create
    # https://myaccount.google.com/apppasswords

    email_receivers = ", ".join(
        toMails
    )  # Join the list of emails into a comma-separated string

    # Set the subject and body of the email
    subject = "Cancel My Subscription!"
    body = """
    Cancel My Subscription please
    """

    em = EmailMessage()
    em["From"] = email_sender
    em["To"] = email_receivers
    em["Subject"] = subject
    em.set_content(body)

    # Add SSL (layer of security)
    context = ssl.create_default_context()

    # Log in and send the email
    with smtplib.SMTP_SSL("smtp.gmail.com", 465, context=context) as smtp:
        smtp.login(email_sender, app_password)
        smtp.sendmail(
            email_sender, toMails, em.as_string()
        )  # Send to the list of emails


# List of email addresses to send the email to
email_list = [
    "[email protected]",
    "[email protected]",
    "[email protected]",
    "[email protected]",
    "[email protected]",
    "[email protected]",
    "[email protected]",
    "[email protected]",
]
email(email_list)
print("Mail has been sent")

1

u/[deleted] Feb 28 '25

Mailjet api is good