Python使用smtplib模組寄送電子郵件的流程詳解

來源:互聯網
上載者:User
1、登入SMTP伺服器
首先使用網上的方法(這裡使用163郵箱,smtp.163.com是smtp伺服器位址,25為連接埠號碼):

import smtplibserver = smtplib.SMTP('smtp.163.com', 25)server.login('j_hao104@163.com', 'password')Traceback (most recent call last): File "C:/python/t.py", line 192, in   server.login('j_hao104@163.com', 'password') File "C:\Python27\lib\smtplib.py", line 622, in login  raise SMTPAuthenticationError(code, resp)smtplib.SMTPAuthenticationError: (535, 'Error: authentication failed')

發現返回:

smtplib.SMTPAuthenticationError: (535, 'Error: authentication failed')

,提示驗證失敗。
有說python不支援SMTP服務,或是服務沒開啟之類的。但是我想起上次我用foxmail登入我的163郵箱的時候,郵箱密碼都輸對了還是提示我密碼錯誤,最後的解決辦法是:像QQ和163郵箱現在都有個用戶端密碼,用第三方登入時需用用戶端密碼登入才行,python也是如此,因此去設定好用戶端密碼,再用用戶端密碼登入。

import smtplibserver = smtplib.SMTP('smtp.163.com', 25)server.login('j_hao104@163.com', 'clientPassword')

此時便返回登入成功提示:

(235, 'Authentication successful')

2、發送郵件

首先使用網上給出的代碼:

import smtplibfrom email.mime.text import MIMETextserver = smtplib.SMTP('smtp.163.com', 25)server.login('j_hao104@163.com', 'clientPassword')msg = MIMEText('hello, send by Python...', 'plain', 'utf-8')server.sendmail('j_hao104@163.com', ['946150454@qq.com'], msg.as_string())

構造MIMEText對象時,第一個參數是郵件內文,第二個參數是MIME的subtype,最後個是編碼方式。
sendmail是發郵件方法,第一個參數是發件郵箱,第二個參數是收件者郵箱,是一個列表,代表可以同時發給多個人,as_string是把MIMEText對象變成str。
但是執行結果並不能得到網上說的結果:

而是:

Traceback (most recent call last): File "C:/python/t.py", line 195, in   server.sendmail('j_hao104@163.com', ['946150454@qq.com'], msg.as_string()) File "C:\Python27\lib\smtplib.py", line 746, in sendmail  raise SMTPDataError(code, resp)smtplib.SMTPDataError: (554, 'DT:SPM 163 smtp11,D8CowEDpDkE427JW_wQIAA--.4996S2 1454562105,please see http://mail.163.com/help/help_spam_16.htm?ip=171.221.144.51&hostid=smtp11&time=1454562105')

網上一查才知道:smtplib.SMTPDataError: (554, 'DT:SPM 163 smtp11……的錯誤是因為信封寄件者和信頭髮件人不匹配。可以看出看出圖片中並沒有寄件者和主題,所以需要對代碼做如下修改:

import smtplibfrom email.header import Headerfrom email.mime.text import MIMETextserver = smtplib.SMTP('smtp.163.com', 25)server.login('j_hao104@163.com', 'clientPassword')msg = MIMEText('hello, send by Python...', 'plain', 'utf-8')msg['From'] = 'j_hao104@163.com 'msg['Subject'] = Header(u'text', 'utf8').encode()msg['To'] = u'飛輪海 'server.sendmail('j_hao104@163.com', ['946150454@qq.com'], msg.as_string())

這樣就能成功發出郵件啦
msg裡的具體資訊可以用一般發郵件方式發封郵件測試下

3、參考樣本

import smtplibfrom email.mime.text import MIMETextto_list = ['123@123.com', '456@456.com']server_host = 'smtp.163.com'username = '你的郵箱帳號'password = '你的郵箱密碼'def send(to_list, sub, content):  '''  :param to_list: 收件者郵箱  :param sub: 郵件標題  :param content: 內容  '''  me = "manager" + "<" + username + ">"   # _subtype 可以設為html,預設是plain  msg = MIMEText(content, _subtype='html')  msg['Subject'] = sub  msg['From'] = me  msg['To'] = ';'.join(to_list)  try:    server = smtplib.SMTP()    server.connect(server_host)    server.login(username, password)    server.sendmail(me, to_list, msg.as_string())    server.close()  except Exception as e:    print str(e)if __name__ == '__main__':  send(to_list, "這個是一個郵件", "

Hello, It's test email.

")
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.