1. 程式人生 > >發郵件的python腳本

發郵件的python腳本

客戶端 divider 發郵件 usr 讓我 郵箱服務器 conn -s tex

1. 編寫一個最簡單的發郵件的python腳本

  1. #coding: utf-8
  2. import smtplib
  3. from email.mime.text import MIMEText
  4. from email.header import Header
  5. sender = ‘[email protected]‘
  6. receiver = ‘[email protected]‘
  7. subject = ‘python email test‘
  8. smtpserver = ‘smtp.163.com‘
  9. username = ‘[email protected]‘
  10. password = ‘*********‘
  11. msg = MIMEText( ‘Hello Python‘, ‘text‘, ‘utf-8‘ )
  12. msg[‘Subject‘] = Header( subject, ‘utf-8‘ )
  13. smtp = smtplib.SMTP()
  14. smtp.connect( smtpserver )
  15. smtp.login( username, password )
  16. smtp.sendmail( sender, receiver, msg.as_string() )
  17. smtp.quit()

2. 運行結果

如果在上述代碼username

password,變量中填寫郵箱的帳號密碼那麽會看到以下報錯:

  1. Traceback (most recent call last):
  2. File "mail.py", line 18, in <module>
  3. smtp.login( username, password )
  4. File "/usr/lib64/python2.6/smtplib.py", line 589, in login
  5. raise SMTPAuthenticationError(code, resp)
  6. smtplib.SMTPAuthenticationError: (535, ‘Error: authentication failed‘)

3. 解決方法

調用163郵箱服務器來發送郵件,我們需要開啟POP3/SMTP服務,這時163郵件會讓我們設置客戶端授權碼,這個授權碼替代上面代碼部分的password即可成功發送郵件

發郵件的python腳本