Send an email to a specific email address with python without SMTP settings

background

Previously, I wrote an article Automatically run a browser on Ubuntu and observe values on the WEB at fixed points. I considered sending an alert by email if there was a noticeable movement in the value I was monitoring, but setting up the SMTP server from scratch was a hassle. When I looked it up, I tried to program it because it is possible to send mail without preparing SMTP by using Gmail API.

environment

OS : Ubuntu16.04 python : version3.5

Step1) Preparation for using Gmai API

(1) Install the Gmail API package for python </ b>

pip3 install --upgrade google-api-python-client

(2) Authenticate using API on Gmail page </ b>

Authentication should be done according to Step 1 on the here page.

Step2) Write the program code to send Gmail

The actual program code was almost imitated from the following site. → Send an email using the Gmail API with Python3 + google-api-python-client It is written in a very easy-to-understand manner.

The program code is shown below. You can use it in your own environment just by changing the four constants (CLIENT_SECRET_FILE, APPLICATION_NAME, MAIL_FROM, MAIL_TO) in the code.

from __future__ import print_function
import httplib2
import os

import apiclient
from apiclient import discovery
import oauth2client
from oauth2client import client
from oauth2client import tools

import base64
from email.mime.text import MIMEText
from email.utils import formatdate
import traceback

try:
    import argparse
    flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
    flags = None

# If modifying these scopes, delete your previously saved credentials
# at ~/.credentials/gmail-python-quickstart.json
SCOPES = 'https://www.googleapis.com/auth/gmail.send'
CLIENT_SECRET_FILE = '<path_to_credintial>.json'
APPLICATION_NAME = '<application_name>'

MAIL_FROM = "<sender email-address>"
MAIL_TO = "<receiver email-address>"

def get_credentials():

    home_dir = os.path.expanduser('~')
    credential_dir = os.path.join(home_dir, '.credentials')
    if not os.path.exists(credential_dir):
        os.makedirs(credential_dir)
    credential_path = os.path.join(credential_dir,
                                   'gmail-send-api.json')

    store = oauth2client.file.Storage(credential_path)
    credentials = store.get()
    if not credentials or credentials.invalid:
        flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
        flow.user_agent = APPLICATION_NAME
        if flags:
            credentials = tools.run_flow(flow, store, flags)
        else: # Needed only for compatibility with Python 2.6
            credentials = tools.run(flow, store)
        print('Storing credentials to ' + credential_path)
    return credentials

def create_message(receiver,subject,mail_str):
    message = MIMEText(mail_str)
    message["from"] = MAIL_FROM
    message["to"] = receiver
    message["subject"] = subject
    message["Date"] = formatdate(localtime=True)

    byte_msg = message.as_string().encode(encoding="UTF-8")
    byte_msg_b64encoded = base64.urlsafe_b64encode(byte_msg)
    str_msg_b64encoded = byte_msg_b64encoded.decode(encoding="UTF-8")

    return {"raw": str_msg_b64encoded}

def send_mail(receiver,subject,mail_str):

    credentials = get_credentials()
    http = credentials.authorize(httplib2.Http())
    service = discovery.build('gmail', 'v1', http=http)

    try:
        result = service.users().messages().send(
            userId = MAIL_FROM,
            body=create_message(receiver,subject,mail_str)
        ).execute()

        print("Message Id: {}" .format(result["id"]))

    except apiclient.errors.HttpError:
        print("-----start trace-----")
        traceback.print_exc()
        print("-----end trace-----")

if __name__ == '__main__':
    send_mail("gano_test\ngano_test2")

As a supplement, enter the following for each of the four constants.

  • CLIENT_SECRET_FILE: Path of the authentication json file downloaded from the GMAIL site in STEP1
  • APPLICATION_NAME: An optional application name. Anything is fine.
  • MAIL_FROM: Sender name. This is the address of the account you logged in to in Step 1.
  • MAIL_TO: Destination. Multiple settings can be made by separating them with commas.

Recommended Posts