Send Gmail at the end of the process [Python]

This time, I learned how to use Gmail with Python a while ago, so I would like to summarize it. Then I made a shell script that executes the command and sends the result by Gmail, so I will introduce it.

reference:

Based on: unoh.github.com by unoh: What you want to do:Monitor the process with Python and send an email using gmail when finished|Sekai Lab: About sending images: Self-study Linux: How to send an email via Gmail with a Python script: Regarding SMTP: Programming and Keio Communication: Sending and receiving gmail with Python: About the handling of Japanese: I tried various ways to send Japanese mail with Python --Qiita:

Send Gmail using Python

First, I copied and pasted the code I referred to and tried to see if it worked, but it worked. All you have to do now is customize it for ease of use when calling it from the outside. In addition, considering the problem of Japanese encoding and security, we have improved it by referring to some sites.

I just picked up the good points, but I will post it for the time being.

sendGmail.py


#!/usr/bin/python
# -*- coding: utf-8 -*-
import smtplib
from email.MIMEText import MIMEText
from email.Header import Header
from email.Utils import formatdate
from platform import python_version
import argparse
import getpass
import codecs

release = python_version()
if release > '2.6.2':
    from smtplib import SMTP_SSL
else:
    SMTP_SSL = None

def create_message(from_addr, sender_name, to_addr, subject, body, encoding):
    msg = MIMEText(body, 'plain', encoding)
    msg['Subject'] = Header(subject, encoding)
    form_jp = u"%s <%s>" % (str(Header(sender_name, encoding)), from_addr)
    msg['From'] = from_addr
    msg['To'] = to_addr
    msg['Date'] = formatdate()
    return msg

def send_via_gmail(from_addr, to_addr, passwd, msg):
    if SMTP_SSL:
        print "send via SSL..."
        s = SMTP_SSL('smtp.gmail.com', 465)
        s.login(from_addr, passwd)
        s.sendmail(from_addr, [to_addr], msg.as_string())
        s.close()
        print 'mail sent!'
    else:
        print "send via TLS..."
        s = smtplib.SMTP('smtp.gmail.com', 587)
        if release < '2.6':
            s.ehlo()
        s.starttls()
        if release < '2.5':
            s.ehlo()
        s.login(from_addr, passwd)
        s.sendmail(from_addr, [to_addr], msg.as_string())
        s.close()
        print "mail sent!"

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Send Gmail.')
    parser.add_argument('-t', '--to', dest='to_addr', type=str,
                        default='Default destination',
                        help='To address')
    parser.add_argument('-s', '--subject', dest='subject', type=str,
                        default='Default title', help='Title')
    parser.add_argument('-b', '--body', dest='body', type=str,
                        default='no message', help='Body of the mail.')
    args = parser.parse_args()

    from_addr = "Gmail address of the sender"
    sender_name=u'Source name'
    print "from: %s <%s>" % (sender_name, from_addr)
    passwd = getpass.getpass()
    to_addr = args.to_addr
    title = args.subject
    body = args.body
    msg = create_message(from_addr, sender_name, to_addr, title, body, 'utf-8')
    send_via_gmail(from_addr, to_addr, passwd, msg)

The version check in the first half may be necessary so much to work in other environments (sorry for copying). Using argparse seems to make it easier to handle options, so I introduced it this time.

By the way, if you use argparse, it is easy to display help,

Selection_008.png

It will be displayed as.

Other than that, the basic parts are almost the same as those of the referenced site. SSL seems to be better in terms of security than TLS. Also, I think that it is difficult to write the password of the Google account directly, so when executing it directly, I accept the input from the keyboard and use getpass so that the typed content is not displayed.

Wait for the process to finish and email us

The reason why I wanted to send an email from Python was because I wanted to let the computer in the laboratory do the time-consuming calculations and receive the results when I got home. why? What a cool thing!

So, this time I will write that part with a shell script. Basically, it targets Python scripts, but considering versatility, the command itself is given as an argument.

Click here for the code.

psWatchMail.sh


if [ $# = 0 ]; then
    echo "need argument 'COMMAND'" 1>&2
    exit 0
else
    COMMAND=$1
fi
subject="command \"${COMMAND}\" done"

result=`${COMMAND}`

wait

sleep 1

python /Path to script/sendGmail.py -t "Destination email address" -s "${subject}" -b "${result}"

echo "${result}"

exit 0

As a result

sh psWatchMail.sh "Command to execute"

By specifying the command, when the command ends, the destination specified in the script

"Command" command to execute "done"

You can send an e-mail with the title and the standard output as the body. At first, I thought about a method to judge whether the process is alive by specifying PID etc., and I was investigating in that direction, but this method is simpler and easier to understand, so I decided to use this method. did. In either case, the drawback is that you can't send an email until the process is completely finished, which is incompatible with the GUI simulations you've made so far. Well, if there is a part that is known to take time from the beginning, if you call sendGmail.py inside the Python script, you can send an email at any time, so that's fine. Probably. Alternatively, you may monitor the CPU usage and determine that it is finished when it falls below a certain threshold. I will think about this a lot.

An execution example is

Selection_009.png

It looks like. Also from the Gmail side

Selection_010.png

And you can see that the email has been sent.

Summary

I summarized how to use Gmail with Python. However, this can be sent not only from Gmail but also from other mail clients. In that case, you can change the mail server address and port number. In my case, I actually make a version of my university email account, and sometimes I type emails from the terminal. It is subtle when asked if it is convenient. However, I think that it is suitable for people who are frustrated because they have to open a heavy site such as login authentication every time. (I think I'm like a small person!) Anyway, now I can play on both my home and lab PCs. I'm not afraid of heavy calculations anymore!

Recommended Posts

Send Gmail at the end of the process [Python]
Python Basic Course (at the end of 15)
Remove specific strings at the end of python
Set the process name of the Python program
the zen of Python
At the time of python update on ubuntu
Send Gmail in Python
python> print> Redirected only at the end of processing?> Run with -u
The process of installing Atom and getting Python running
Send and receive Gmail via the Gmail API using Python
Tasks at the start of a new python project
Towards the retirement of Python2
About the ease of Python
About the features of Python
The Power of Pandas: Python
Send using Python with Gmail
Decorator that displays "FIN method name" at the end of the method
Debug by attaching to the Python process of the SSH destination
The process of making Python code object-oriented and improving it
How to insert a specific process at the start and end of spider with scrapy
The story of Python and the story of NaN
First Python 3 ~ The beginning of repetition ~
Existence from the viewpoint of Python
pyenv-change the python version of virtualenv
Change the Python version of Homebrew
Process the result of% time,% timeit
[Python] Understanding the potential_field_planning of Python Robotics
Review of the basics of Python (FizzBuzz)
About the basics list of Python basics
[Python] Create API to send Gmail
Send email via gmail with Python 3.4.3.
Learn the basics of Python ① Beginners
Clean up the repository at the end of the year and delete DS.store
I want to improve efficiency with Python even in the experimental system (5) I want to send a notification at the end of the experiment with the slack API
Change the length of Python csv strings
Check the behavior of destructor in Python
What is the XX file at the root of a popular Python project?
[Python3] Understand the basics of Beautiful Soup
Pass the path of the imported python module
Send newsletters all at once with Gmail
The story of making Python an exe
Implement part of the process in C ++
Learning notes from the beginning of Python 1
Check the existence of the file with python
About the virtual environment of python version 3.7
Shout Hello, Reiwa! At the beginning of Reiwa
[Python] Understand the content of error messages
Where is the python instantiation process written?
[Python3] Rewrite the code object of the function
Post the subject of Gmail on twitter
I didn't know the basics of Python
The result of installing python in Anaconda
[Python] Try pydash of the Python version of lodash
[python] Checking the memory consumption of variables
Check the path of the Python imported module
The story of manipulating python global variables
[python] [meta] Is the type of python a type?
Call the python debugger at any time
The basics of running NoxPlayer in Python
Pandas of the beginner, by the beginner, for the beginner [Python]
The Python project template I think of.