Skip to content

Instantly share code, notes, and snippets.

@AJNOURI
Last active November 7, 2018 07:28
Show Gist options
  • Save AJNOURI/2cca62f1f42960c5874f1fa771b95d86 to your computer and use it in GitHub Desktop.
Save AJNOURI/2cca62f1f42960c5874f1fa771b95d86 to your computer and use it in GitHub Desktop.
Python script to send email using gmail
#!/usr/bin/python
import smtplib
import socket
import subprocess
#######################################################
# Make sure your provider allows outgoing SMTP trafic
#######################################################
# Manually add the script to CRONTAB to be run every ex:5 hours: (crontab -e)
# 0 */5 * * * root /root/warnme.py
# Get the hostname
hostname = socket.gethostname()
# ################################################################################
# Put here the data you need to communicate
# Example: Warn a cloud user that there is active VM resource (consuming money)
#
# Get the public IP address
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80))
ipaddress = s.getsockname()[0]
s.close()
# Get uptime of the VM
uptime = subprocess.check_output(['uptime']).decode("ASCII")
# ################################################################################
# For GMAIL: turn on access to less secure applications (required)
# Build the message
# PUT YOUR OWN SENDER, RECEIVER AND PASSWORD INFOMATION
sender = "sender@sendermail.com"
recipient = "receiver@receivergmail.com"
password = "senderpassword"
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
subject = "WARNING! Server resource active"
text = "HOSTNAME: " + hostname +"\nIP : " + ipaddress + "\nUPTIME: " + uptime
# Authticating & Sending the mail
smtp_server = smtplib.SMTP_SSL("smtp.gmail.com", 465)
smtp_server.login(sender, password)
message = "Subject: {}\n\n{}".format(subject, text)
smtp_server.sendmail(sender, recipient, message)
smtp_server.close()
@AJNOURI
Copy link
Author

AJNOURI commented Nov 7, 2018

selection_005_07_11

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment