Send mass email with python and gmail
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 encodersmsg[‘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’
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.