Skip to content

Instantly share code, notes, and snippets.

@walbon
Created July 20, 2012 20:13
Show Gist options
  • Save walbon/3152962 to your computer and use it in GitHub Desktop.
Save walbon/3152962 to your computer and use it in GitHub Desktop.
Script to send messages by sendmail and smtplib, using python.
#!/usr/bin/python
#
# Author: Gustavo Walbon ( [email protected] )
#
# Import smtplib for the actual sending function
import smtplib
import sys
# Import the email modules we'll need
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from optparse import OptionParser
def main():
parser = OptionParser(usage="""\
It is necessary define the options to send message.
Usage: %prog -l Level -s "Subject" -t "user@server" -f "me@local" -m "Message"\
""")
parser.add_option('-l', '--lvl',type='string', action='store',help=""" Indicates the level of message, WARN, ERROR or OK.""")
parser.add_option('-s', '--sub',type='string', action='store',help=""" Subject of message. """)
parser.add_option('-t', '--to',type='string', action='store',help=""" Destination of message that will be send. """)
parser.add_option('-f', '--frm',type='string', action='store',help=""" Who are that be sending the email. """)
parser.add_option('-m', '--msg', type='string', action='store', help=""" The body message to send. """)
(opts, args) = parser.parse_args()
if not opts.lvl or not opts.sub or not opts.frm or not opts.msg or not opts.to :
parser.print_help()
sys.exit(1)
msg = MIMEMultipart('alternative')
if opts.lvl == "WARN":
msg['Subject'] = "[WARNING] " + opts.sub
msg['X-Priority'] = '1'
msg['X-MSMail-Priority'] = 'High'
elif opts.lvl == "ERROR":
msg['Subject'] = "[ERROR] " + opts.sub
msg['X-Priority'] = '1'
msg['X-MSMail-Priority'] = 'High'
elif opts.lvl == "OK":
msg['Subject'] = opts.sub
else:
print "\n [!] Wrong level \n"
parser.print_help()
return -1
msg['From'] = opts.frm
msg['To'] = opts.to
body = MIMEText(opts.msg, 'plain')
msg.attach(body)
# Send the message via local SMTP server.
s = smtplib.SMTP('localhost')
# sendmail function takes 3 arguments: sender's address, recipient's address
# and message to send - here it is sent as one string.
try:
Response = s.sendmail(opts.frm, opts.to, msg.as_string())
print "\n[OK] Sent email.\n"
except(smtplib.SMTPException), error:
print "\n[!!] Sorry, we had a problem while tried send a email.\n"
print error
print "\n"
s.quit()
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment