Send mass email with python and gmail

Dr. Beynis (PhD)
2 min readFeb 2, 2023

--

1- You will need to import the following library and modules with:

import smtplib

# Helper email modules
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders

2- You will define the subject, recipient, sender, body etc of the email with:

msg[‘Subject’] = “Your message subject”

email_recipients = [Array of comma separated string=> the emails]

msg = MIMEMultipart()

#MIMEmultipart will separate parts of the text body from others

msg[‘From’] = “My@email.com” #Your email

msg[‘Subject’] = subject

body = ‘Dear Administrator, \n\n I am Dr. Beynis, Cheers\n\n Sincerely’ #this is an example.

3- You will attach and call servers to send the email:

msg.attach(MIMEText(body,’plain’))
text = msg.as_string()
server = smtplib.SMTP(‘smtp.gmail.com’,587)
server.starttls()
server.login(email_user,email_password)
server.sendmail(email_user,email_send,text)
server.quit()

The entire script is:

import smtplib

# Helper email modules
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders

msg[‘Subject’] = “Your message subject”

email_recipients = [Array of comma separated string=> the emails]

msg = MIMEMultipart()

#MIMEmultipart will separate parts of the text body from others

msg[‘From’] = “My@email.com” #Your email

msg[‘Subject’] = subject

body = ‘Dear Administrator, \n\n I am Dr. Beynis, Cheers\n\n Sincerely’ #this is an example.

msg.attach(MIMEText(body,’plain’))
text = msg.as_string()
server = smtplib.SMTP(‘smtp.gmail.com’,587)
server.starttls()
server.login(email_user,email_password)
server.sendmail(email_user,email_send,text)
server.quit()

4 - In general executing the script will generate an error of this sort:

error (535, b'5.7.8 username and password not accepted.

5- You will:

a - Go to Google Account Page>Security>Signing in to Google section

b - turn on Step Verification. This feature will be on.

c- go to App Password and generate new-app-password for mail access. It will generate a code for you, then use this password as the value of email_password in Python.

email_password=’copied_and_pasted_google_generated_code’

App passwords in Google sign in

Finally try again after you see this as output:

(221,
b'2.0.0 closing connection v1-20020ae9e301000000b007062139ecb3sm6572203qkf.95 - gsmtp')

Check your mailbox, you should see your email has been sent.

--

--

Dr. Beynis (PhD)
Dr. Beynis (PhD)

Written by Dr. Beynis (PhD)

I am Christian Beynis. I went from obtaining a physics PhD to trying out different career paths learning new skills and becoming a freelancer. github/chrisb5a

No responses yet