Advertisement
Guest User

Untitled

a guest
Mar 21st, 2018
691
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.90 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # encoding: utf-8
  3. """
  4. python_3_email_with_attachment.py
  5. Created by Robert Dempsey on 12/6/14.
  6. Copyright (c) 2014 Robert Dempsey. Use at your own peril.
  7.  
  8. This script works with Python 3.x
  9.  
  10. NOTE: replace values in ALL CAPS with your own values
  11. """
  12.  
  13. import os
  14. import smtplib
  15. from email import encoders
  16. from email.mime.base import MIMEBase
  17. from email.mime.multipart import MIMEMultipart
  18. import time
  19.  
  20. COMMASPACE = ', '
  21.  
  22. def main():
  23.     sender = 'osher10g@gmail.com'
  24.     gmail_password = 'o1s2h3e4r5'
  25.     recipients = ['osherg10@gmail.com', 'ron200011@gmail.com']
  26.    
  27.     # Create the enclosing (outer) message
  28.     outer = MIMEMultipart()
  29.     outer['Subject'] = 'EMAIL SUBJECT'
  30.     outer['To'] = COMMASPACE.join(recipients)
  31.     outer['From'] = sender
  32.     outer.preamble = 'You will not see this in a MIME-aware mail reader.\n'
  33.  
  34.     # List of attachments
  35.     attachments = ['python.png']
  36.  
  37.     # Add the attachments to the message
  38.     for file in attachments:
  39.         try:
  40.             with open(file, 'rb') as fp:
  41.                 msg = MIMEBase('application', "octet-stream")
  42.                 msg.set_payload(fp.read())
  43.             encoders.encode_base64(msg)
  44.             msg.add_header('Content-Disposition', 'attachment', filename=os.path.basename(file))
  45.             outer.attach(msg)
  46.         except:
  47.             print("Couldn't send email")
  48.             raise
  49.  
  50.     composed = outer.as_string()
  51.  
  52.     # Send the email
  53.     try:
  54.         with smtplib.SMTP('smtp.gmail.com', 587) as s:
  55.             s.ehlo()
  56.             s.starttls()
  57.             s.ehlo()
  58.             s.login(sender, gmail_password)
  59.             s.sendmail(sender, recipients, composed)
  60.             s.close()
  61.         print("Email sent!")
  62.     except:
  63.         print("Unable to send the email. Error: ")
  64.         raise
  65.  
  66. if __name__ == '__main__':
  67.     for x in range (2):
  68.         main()
  69.         time.sleep(60)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement