skip to content

Python: Sending Email with Google SMTP

/ 1 min read

Pacakge Requirements:

  • python-dotenv: pip install python-dotenv

Python Code

import smtplib
import dotenv
import os
import csv
import time

dotenv.load_dotenv()

EMAIL = os.getenv('EMAIL')
PASSWORD = os.getenv('PASSWORD')

def log(message):
    print(message)


log('Starting the program...')
log(f'Email: {EMAIL}')
log(f'Password: {PASSWORD}')


server = smtplib.SMTP('smtp.gmail.com', 587)

subject = 'Request for.......... COMPLETE SUBJECT'
header = 'From: ' + EMAIL + '\n' + 'To: ' + '[RECEPIENT]' + '\n' + 'Subject: ' + subject + '\n'
message = '''Dear [RECEPIENT],
REMAINNING TEXT HERE

Warm regards,
[Your Name]
'''

def read_csv_and_send():
    with open('recepient.csv', 'r') as file:
        log('Reading CSV file...')
        reader = csv.reader(file)
        next(reader) # Comment this line if you don't have header in your csv file
        for row in reader:
            recepient = row[0]
            email = row[1]
            send_email(recepient, email)
            time.sleep(1)
    log('All emails sent')
            

def login():
    try:
        server.ehlo()
        server.starttls()
        server.login(EMAIL, PASSWORD)
        log('Login successful')
    except Exception as e:
        log(f'Error: {e}')


def send_email(recepient, email):
    text = header.replace('[RECEPIENT]', email) + '\n' + message.replace('[RECEPIENT]', recepient)
    server.sendmail(EMAIL, email, text)
    print(f'Email sent to {recepient}: {email}')
    
if __name__ == '__main__':
    login()
    read_csv_and_send()

recepeint.csv

Name, Email
Recepient Name, recpemail@email.com

.env

EMAIL=youremail@email
PASSWORD=yourpassword