Advertisement
rfmonk

smtplib_authenticated.py

Feb 21st, 2014
131
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.10 KB | None | 0 0
  1. #!/usr/bin/env python
  2.  
  3.  
  4. import smtplib
  5. import email.utils
  6. from email.mime.text import MIMEText
  7. import getpass
  8.  
  9. # Prompt the user for connection info
  10. to_email = raw_input('Recipient: ')
  11. servername = raw_input('Mail server name: ')
  12. username = raw_input('Mail username: ')
  13. password = getpass.getpass("%s's password: " % username)
  14.  
  15. # Create the message
  16. msg = MIMEText('Test message from PyMOTW.')
  17. msg.set_unixfrom('author')
  18. msg['To'] = email.utils.formataddr(('Recipient', to_email))
  19. msg['From'] = email.utils.formataddr(('Author',
  20.                                       'author@example'))
  21. msg['Subject'] = 'Test from PyMOTW'
  22.  
  23. server = smtplib.SMTP(servername)
  24. try:
  25.     server.set_debuglevel(True)
  26.  
  27.     # identify ourselves, prompting server for supported features
  28.     server.ehlo()
  29.  
  30.     # If we can encrypt this session, do it
  31.     if server.has_extn('STARTTLS'):
  32.         server.starttls()
  33.         server.ehlo()  # reidentify ourselves over TLS connection
  34.  
  35.     server.login(username, password)
  36.     server.sendmail('author@example.com',
  37.                     [to_email],
  38.                     msg.as_string())
  39. finally:
  40.     server.quit()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement