Python: Simple Email Gmail

Sometimes it is very useful to have the script that sends notification, when finishes executing, has come to an error or just needs to send some data to you.This script is used to send a simple email from a gmail account (can be configured for other email servers).

I was working on the task, that involved Cisco ISE, guest portal and python – love it. This part will cover only Python and send email feature.

If you have 2FA enabled (you should have it enabled 🙂 ), an app password needs to be generated.

Go to: https://myaccount.google.com/
Security > Signing in to Google > App password. Select the app name and device you want to generate the app password for and Generate the password.

Here is a simple Python script to send an email:

import smtplib

def send_email():
    fromaddr = "YOUR_EMAIL@GMAIL.COM"
    toaddr = "SOMEONE_EMAIL@DOMAIN.COM"

    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.ehlo()
    server.starttls()
    server.ehlo()
    server.login(fromaddr, "YOUR_GMAIL_APP_PASSWORD")
    SUBJECT = "SUBJECT"
    TEXT = "TEXT"
    message = 'Subject: {}\n\n{}'.format(SUBJECT, TEXT)
    server.sendmail(fromaddr, toaddr, message)
    server.quit()
Share

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *