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:
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,
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.
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
It looks like. Also from the Gmail side
And you can see that the email has been sent.
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