Advertisement
ChrisProsser

send_email.py

Jun 28th, 2013
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.83 KB | None | 0 0
  1. #!/usr/bin/python
  2.  
  3. # currently set up and tested on gmail only
  4.  
  5. import smtplib
  6. from email.MIMEMultipart import MIMEMultipart
  7. from email.MIMEBase import MIMEBase
  8. from email.MIMEText import MIMEText
  9. from email import Encoders
  10. import os, sys, base64
  11.  
  12. def mail(gmail_user, enc_pwd, to, subject, body, attach):
  13.     msg = MIMEMultipart()
  14.  
  15.     msg['From'] = gmail_user
  16.     msg['To'] = to
  17.     msg['Subject'] = subject
  18.     msg.attach(MIMEText(body, 'html'))
  19.  
  20.     if attach:
  21.         part = MIMEBase('application', 'octet-stream')
  22.         part.set_payload(open(attach, 'rb').read())
  23.         Encoders.encode_base64(part)
  24.         part.add_header('Content-Disposition',
  25.                'attachment; filename="%s"' % os.path.basename(attach))
  26.         msg.attach(part)
  27.  
  28.     mailServer = smtplib.SMTP("smtp.gmail.com", 587)
  29.     mailServer.ehlo()
  30.     mailServer.starttls()
  31.     mailServer.ehlo()
  32.     mailServer.login(gmail_user, base64.b64decode(enc_pwd))
  33.     mailServer.sendmail(gmail_user, to, msg.as_string())
  34.     mailServer.close()
  35.  
  36. def main():
  37.     if len(sys.argv) <6:
  38.         print "Usage: send_email.py <from> <enc_pwd> <to> <subject> <body> " \
  39.               "[<attachments>]"
  40.         print "Note: Email is being sent in html mode, so any newlines should " \
  41.               "be sent as <br/>"
  42.         if len(sys.argv) > 1:
  43.             print "\nThe following arguements were received:"
  44.             for i in sys.argv:
  45.                 print i
  46.     else:
  47.         gmail_user  = sys.argv[1]
  48.         gmail_pwd   = sys.argv[2]
  49.         to          = sys.argv[3]
  50.         subject     = sys.argv[4]
  51.         body        = sys.argv[5]
  52.         attach      = None
  53.         if len(sys.argv) >= 7:
  54.             attach  = sys.argv[6]
  55.        
  56.         mail(gmail_user, gmail_pwd, to, subject, body, attach)
  57.  
  58. if __name__ == '__main__':
  59.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement