Send email to different people with Python

I made a post about sending email with python last year, now I want to make a step further: send more emails at the same time to different people (nothing to do with bothering people, but, in my case, to send different tasks to different students).

I made two function, the first to send the same message to everybody, but this is not so useful as you can do it with regular email (even if using python makes it more easy, so it can come handy for someone), the second to send different messages to each address with one run of the script. This last option is what I needed and I think its pretty cool.

To get the password

  • Go into gmail
  • go on the to right corner where is your avatar and choose Manage your google account
  • check security on the left menu that appears on the page
  • choose app password (in the middle of the page)
  • insert your google password
  • in the page, go to the bottom, choose app=mail, device=…. what you want to use
  • click on generate
  • copy the password in the code below where there is password=”**********”

Here is the code

import smtplib

# change this one with your address
mail = "[email protected]"
# and this with the password as I showed you in the video
password = "*********"

message = [
    """From: From Person <[email protected]>
To: To Person <[email protected]>
Subject: Email 1

First email
    """,

    """From: From Person <[email protected]>
To: To Person <[email protected]>
Subject: Email 2 from gg

Second email again
    """]

mail = username
receivers = [mail, "[email protected]"]


def same_email():
    server = smtplib.SMTP("smtp.gmail.com", 587)
    server.ehlo()
    server.starttls()
    server.ehlo()
    server.login(username, password)
    server.sendmail(
        mail,
        receivers,
        message)

    server.quit()


def different_email():
    for n, msg in enumerate(message):
        server = smtplib.SMTP("smtp.gmail.com", 587)
        server.ehlo()
        server.starttls()
        server.ehlo()
        server.login(username, password)
        server.sendmail(
            mail,
            receivers[n],
            message[n])

        server.quit()


different_email()

 

Here is the video

See ya next time. Do not forget to subscribe.


Subscribe to the newsletter for updates
Tkinter templates
Avatar My youtube channel

Twitter: @pythonprogrammi - python_pygame

Videos

Speech recognition game

Pygame's Platform Game

Other Pygame's posts

Published by pythonprogramming

Started with basic on the spectrum, loved javascript in the 90ies and python in the 2000, now I am back with python, still making some javascript stuff when needed.