send_mail.py 857 B

12345678910111213141516171819202122232425262728
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. from email import encoders
  4. from email.header import Header
  5. from email.mime.text import MIMEText
  6. from email.utils import parseaddr, formataddr
  7. import smtplib
  8. def _format_addr(s):
  9. name, addr = parseaddr(s)
  10. return formataddr((Header(name, 'utf-8').encode(), addr))
  11. from_addr = input('From: ')
  12. password = input('Password: ')
  13. to_addr = input('To: ')
  14. smtp_server = input('SMTP server: ')
  15. msg = MIMEText('hello, send by Python...', 'plain', 'utf-8')
  16. msg['From'] = _format_addr('Python爱好者 <%s>' % from_addr)
  17. msg['To'] = _format_addr('管理员 <%s>' % to_addr)
  18. msg['Subject'] = Header('来自SMTP的问候……', 'utf-8').encode()
  19. server = smtplib.SMTP(smtp_server, 25)
  20. server.set_debuglevel(1)
  21. server.login(from_addr, password)
  22. server.sendmail(from_addr, [to_addr], msg.as_string())
  23. server.quit()