Last active
August 17, 2016 23:13
-
-
Save chaonan99/760e0edb9fad982739a586f08a43be7f to your computer and use it in GitHub Desktop.
Send email notification after finishing some shell command
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
New security policy don't support (username, password) to access gmail account for third-party application. | |
When you attempt to use gmail to send notification, it may give a smtplib.SMTPAuthenticationError. You have | |
two options to fix this. | |
1. At http://www.google.com/settings/security/lesssecureapps | |
enable less secure application access then you can use this script. | |
2. Follow http://stackoverflow.com/questions/25944883/how-to-send-an-email-through-gmail-without-enabling-insecure-access | |
and use gmail_notify.py script. | |
[Description] Send email notificaton after the program finished | |
[Author] chaonan99 | |
[Date] 08/10/2016 | |
[Contact] [email protected] | |
[Acknowledge] https://github.com/raingo/TGIF-Release/blob/master/code/gifs-filter/email_notify.py | |
""" | |
import smtplib,sys,socket,optparse,os | |
import subprocess as sp | |
parser = optparse.OptionParser() | |
# Remember to change this to your address or it will be sent to me :-) | |
parser.add_option('-a', '--address', dest='address', help='Email address of receiver', default='[email protected]') | |
parser.add_option('-i', '--id', dest='id', help='app id', default='some app') | |
parser.add_option('-c', '--command', dest='command', help='command string (Recommand using single quote)', \ | |
default='ls') # you can add command here, or type command in command line | |
(opts, args) = parser.parse_args() | |
hostname = socket.gethostname() | |
# Change directory here | |
# os.chdir("/home/Public/chaonan99") | |
cwd = os.getcwd() | |
# Change FROM, username, pwd fields to whom send the email | |
config = { | |
'HOST': 'smtp.gmail.com', | |
'port': 587, | |
'FROM': '"%s ALERT" <[email protected]>' % opts.id, | |
'TO': opts.address, | |
'SUBJECT':'New Notification Event From [%s]' % opts.id, | |
'username': '[email protected]', | |
'pwd': 'somepassword', | |
} | |
session = smtplib.SMTP(config['HOST'], config['port']) | |
session.ehlo() | |
session.starttls() | |
session.ehlo() | |
session.login(config['username'], config['pwd']) | |
headers = ["from: " + config['FROM'], "subject: " + config['SUBJECT'], "to: " + config['TO'], "mime-version: 1.0", "content-type: text/html"] | |
headers = "\r\n".join(headers) | |
msg = '\r\n\r\n from ' + hostname + ' \r\n\r\n at ' + cwd | |
# Execute command | |
sp.call(opts.command.split(" "), stderr = sp.STDOUT) | |
# Send email | |
session.sendmail(config['FROM'], config['TO'], headers + "\r\n\r\n" + msg) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
New security policy don't support (username, password) to access gmail account for third-party application. | |
When you attempt to use gmail to send notification, it may give a smtplib.SMTPAuthenticationError. You have | |
two options to fix this. | |
1. At http://www.google.com/settings/security/lesssecureapps | |
enable less secure application access then you can use the previous email_notify.py script. | |
2. Follow http://stackoverflow.com/questions/25944883/how-to-send-an-email-through-gmail-without-enabling-insecure-access | |
and use this script. | |
[Description] Send email notificaton after the program finished | |
[Author] chaonan99 | |
[Date] 08/17/2016 | |
[Contact] [email protected] | |
""" | |
import base64 | |
import httplib2,sys,socket,argparse,os | |
import subprocess as sp | |
from email.mime.text import MIMEText | |
from apiclient.discovery import build | |
from oauth2client.client import flow_from_clientsecrets | |
from oauth2client.file import Storage | |
from oauth2client.tools import run_flow | |
# Remember to change this to your address or it will be sent to me :-) | |
parser = argparse.ArgumentParser() | |
parser.add_argument('-a', '--address', help='Email address of receiver', default='') | |
parser.add_argument('-i', '--id', help='app id', default='some app') | |
parser.add_argument('-c', '--command', help='command string (Recommand using single quote)', \ | |
default='ls') # you can add command here, or type command in command line | |
args = parser.parse_args() | |
# Path to the client_secret.json file downloaded from the Developer Console | |
CLIENT_SECRET_FILE = '../client_secret_336762324219-m8m0as46k94vjidrfq8samuk086o2f0g.apps.googleusercontent.com.json' | |
# Check https://developers.google.com/gmail/api/auth/scopes for all available scopes | |
OAUTH_SCOPE = 'https://www.googleapis.com/auth/gmail.compose' | |
# Location of the credentials storage file | |
STORAGE = Storage('gmail.storage') | |
# Start the OAuth flow to retrieve credentials | |
flow = flow_from_clientsecrets(CLIENT_SECRET_FILE, scope=OAUTH_SCOPE) | |
http = httplib2.Http() | |
# Try to retrieve credentials from storage or run the flow to generate them | |
credentials = STORAGE.get() | |
if credentials is None or credentials.invalid: | |
credentials = run_flow(flow, STORAGE, http=http) | |
# Authorize the httplib2.Http object with our credentials | |
http = credentials.authorize(http) | |
# Build the Gmail service from discovery | |
gmail_service = build('gmail', 'v1', http=http) | |
# Change directory here | |
# os.chdir("/home/Public/chaonan99") | |
# Execute command | |
exit_code = sp.call(args.command.split(" "), stderr = sp.STDOUT) | |
# create a message to send (define your own message!) | |
hostname = socket.gethostname() | |
cwd = os.getcwd() | |
if exit_code == 0: | |
message = MIMEText('\r\n\r\n from ' + hostname + ' \r\n\r\n at ' + cwd + ". Program done") | |
else: | |
message = MIMEText('\r\n\r\n from ' + hostname + ' \r\n\r\n at ' + cwd + ". An error occur") | |
message['to'] = args.address | |
message['from'] = '"%s ALERT" <[email protected]>' % args.id | |
message['subject'] = 'New Notification Event From [%s]' % args.id | |
body = {'raw': base64.b64encode(message.as_string())} | |
# send it | |
try: | |
message = (gmail_service.users().messages().send(userId="me", body=body).execute()) | |
print('Message Id: %s' % message['id']) | |
print(message) | |
except Exception as error: | |
print('An error occurred: %s' % error) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment