Friday, July 7, 2023

Send an email to a list of email addresses using python and Gmail


Before sending emails using Gmail and python, you will need to enable the 2-step Verification.

Enable 2-step Verification:

1. To Enable 2-step Verification in your google account, go to Gmail.

2. Click on the "profile picture" > "Manage your Google Account"  in top right corner.


3. Now you will be taken to the Settings Screen. On left hand of this screen, there are various options. Click on Security from Left side Tab and scroll down to "How you sign in to Google". 

4. Click on the Arrow to right side of 2-step Then click and Enable the "2-step Verification". It may ask you for your Google account's password for confirmation.

5. Once you have enabled 2-step Verification, scroll down to "App passwords" and under the "App password", click on the arrow to right.


6. Now you will able to create passwords for your Apps. After clicking on the arrow, you will taken to following screen.

7. Here, you will select "Mail" from drop down menu in "Select App" box.

8.  Select "Other" from drop down menu of "Select device".


9. Now enter a custom name for your app in the window shown below and click on "Generate" button to create a password for your custom app.

 

10. Copy and save the password shown in the next window in a text file or where-ever you like. This password will be used in our python code as password to login into your Gmail account.


Code to send Emails:

The following code will send emails to the group separated by a time of 40+ seconds.

Note:
The program contains a list named "mail_list" to send emails to each of these. You can replace them with your own list of emails. A file named "file.txt" is also attached to the email. This 'file.txt' can be changed to any file with allowable size.

You will replace the "from@sender.com" with your own Gmail address and 'password' with password obtained in step 10.

Replace 'Email Subject' with your own email subject and 'email body text' with your email body text. For 'email body text', \n may be inserted to write to a new line.

Since all of the above mentioned changes are in string format, so they should be enclosed in ' ' to keep them in string format.

import smtplib
from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import time

mail_list = ['example1@domain1.com',
             'example2@domain1.com',
             'example3@domain1.com']

for rec_email in mail_list:
    sender_email = "from@sender.com"
    sender_password = 'password'
    recipient_email = rec_email
   
    subject = 'Email Subject'
    body = 'email body text'
   
    attachmentFile = 'file.txt'
    with open(attachmentFile, "rb") as attachment:
       
        # Adding the attachment
        part = MIMEBase("application", "octet-stream")
        part.set_payload(attachment.read())
    encoders.encode_base64(part)
    part.add_header(
        "Content-Disposition",
        f"attachment; filename = {attachmentFile}",
    )

    message = MIMEMultipart()
    message['Subject'] = subject
    message['From'] = sender_email
    message['To'] = recipient_email
    html_part = MIMEText(body)
    message.attach(html_part)
    message.attach(part)

    with smtplib.SMTP_SSL('smtp.gmail.com', 465) as server:
            try:
                server.login(sender_email, sender_password)
                server.sendmail(sender_email,
                                recipient_email, message.as_string())
            except Exception as e:
                print(getattr(e, 'message', repr(e)))
    print(f'sent to {recipient_email}')
    #wait for 40+ seconds before sending second email
    time.sleep(40 + (random.randint(0,9)))