天天看點

python發送email郵件

一.開啟郵箱SMTP服務

發送郵件需要使用SMTP伺服器,常用的免費伺服器有:163、126、qq等郵箱。

QQ郵箱配置方式如下:

1) 登入qq郵箱,選擇【設定】-【賬戶】

python發送email郵件

2) 在POP3/IMAP/SMAP/Exchage/CardDAV/CalDAV服務中,找到POP3/SMTP服務和IMAP/SMTP服務,點選開啟。

python發送email郵件

python發送email郵件

python發送email郵件

163郵箱配置方式如下:

1)注冊163郵箱,登入後設定。

python發送email郵件

2) 在新頁面點選“用戶端授權密碼”,勾選“開啟”,彈出新視窗填寫手機驗證碼。

python發送email郵件

3) 填寫授權碼

python發送email郵件

4) 提示開啟成功。

python發送email郵件

二、使用python發送郵件

  • 使用python自帶的子產品:smptlib、email
import smtplib
from email.mime.text import MIMEText
from email.header import Header      

1、發送普通的郵件

# 發送郵件的步驟
import smtplib
from email.mime.text import MIMEText     # 用來構造文本類型的郵件
from email.header import Header          # 用來構造郵件的頭部
# 第一步:建立一個SMTP的對象
s = smtplib.SMTP()
# 第二步:連接配接到SMTP的伺服器
host = 'smtp.163.com'    # 設定163郵箱伺服器,端口為:25
port = 25
#  host = 'smtp.qq.com'  port = 465  # 設定qq郵箱伺服器,端口為:465
s.connect(host,port)       # 連接配接伺服器
# s.connect(host = 'smtp.163.com',port = 25)
# 第三步:登入SMTP伺服器
mail_user = '[email protected]'           # 163郵箱的使用者名
mail_pass = 'password'                      # 注意:此處填寫的是郵箱的SMTP伺服器授權碼
s.login(user=mail_user,password=mail_pass)
# 第四步:建構郵件内容
content = '使用python測試發送郵件'             # 建構郵件内容
msg = MIMEText(content,_charset='utf8')     # _charset 指定編碼格式
msg['Subject'] = Header('測試報告','utf8')   # 郵件主題
msg['From'] = '[email protected]'       # 發件人郵箱,可傳入清單,用于給多個人發送檔案
msg['To'] = '[email protected]'             # 收件人

# 第五步:發送郵件
s.sendmail(from_addr=msg['From'],to_addrs=msg['To'],msg=msg.as_string())     #将郵件内容轉換為字元串      

2、發送HTML格式郵件及附件

import smtplib
from email.mime.text import MIMEText     # 文本類型的郵件,用來構造郵件
from email.header import Header          # 用來構造郵件的頭部
from email.mime.application import MIMEApplication   
from email.mime.multipart import MIMEMultipart  # 用來構造附件

# 發送郵件的步驟
# 第一步:建立一個SMTP的對象
s = smtplib.SMTP()
# 第二步:連接配接到SMTP的伺服器
host = 'smtp.163.com'    # 設定163郵箱伺服器,端口為:25
port = 25
#  host = 'smtp.qq.com'    # 設定qq郵箱伺服器,端口為:465
s.connect(host,port)   # 連接配接伺服器
# 第三步:登入SMTP伺服器
mail_user = '[email protected]'     # 163郵箱的使用者名
mail_pass = 'wl987654321'               # 注意:此處填寫的是郵箱的SMTP伺服器授權碼
s.login(user=mail_user,password=mail_pass)

# 構造文本郵件内容
content = '使用python測試發送郵件'             # 建構郵件内容
textcontent = MIMEText(content,_charset='utf8')        # _charset 指定編碼格式
# 構造附件(二進制位元組流形式)
part = MIMEApplication(open("report.html",'rb').read(),_subtype=None) 
# part = MIMEApplication(open("report.html",'rb').read()) 需要檢視_subtype=None 是否會引發異常
part.add_header('content-disposition', 'attachment', filename='report18.html')  # 對方收到郵件之後,附件在郵件中顯示的名稱
# 封裝一封郵件
msg = MIMEMultipart()
# 加入文本内容
msg.attach(textcontent)
msg.attach(part)
# 發送郵件
msg['From'] = '[email protected]'       #發件人郵箱
msg['To'] = '[email protected]'             #收件人

#第五步:發送郵件
s.sendmail(from_addr='[email protected]',to_addrs='[email protected]',msg=msg.as_string())      # 将郵件内容轉換為字元串
  定義send_email函數
import smtplib
from email.mime.text import MIMEText     #文本類型的郵件,用來構造郵件
from email.header import Header          #用來構造郵件的頭部
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart  #用來構造附件

def send_email(filepath):
    """
    :param filepath:   #傳入報告檔案的路徑
    :return:
    """
    # 發送郵件的步驟
    # 第一步:建立一個SMTP的對象
    s = smtplib.SMTP()
    # 第二步:連接配接到SMTP的伺服器
    host = 'smtp.163.com'    #設定163郵箱伺服器,端口為:25
    port = 25
    #  host = 'smtp.qq.com'    #設定qq郵箱伺服器,端口為:465
    s.connect(host,port)   #連接配接伺服器
    # 第三步:登入SMTP伺服器
    mail_user = '[email protected]'     #163郵箱的使用者名
    mail_pass = 'wl987654321'               #注意:此處填寫的是郵箱的SMTP伺服器授權碼
    s.login(user=mail_user,password=mail_pass)

    #構造文本郵件内容
    content = '使用python測試發送郵件'             #建構郵件内容
    textcontent = MIMEText(content,_charset='utf8')        #_charset 指定編碼格式
    #構造附件(二進制位元組流形式)
    part = MIMEApplication(open(filepath,'rb').read())
    part.add_header('content-disposition', 'attachment', filename='report988.html')  #對方收到郵件之後,附件在郵件中顯示的名稱
    # 封裝一封郵件
    msg = MIMEMultipart()
    #加入附件和文本内容
    msg.attach(textcontent)
    msg.attach(part)
    #發送郵件
    msg['From'] = '[email protected]'       #發件人郵箱
    msg['To'] = '[email protected]'             #收件人

    #第五步:發送郵件
    s.sendmail(from_addr=msg['From'],to_addrs=msg['To'],msg=msg.as_string())      #将郵件内容轉換為字元串

send_email('report.html')      

定義send_email函數

import smtplib
from email.mime.text import MIMEText     # 文本類型的郵件,用來構造郵件
from email.header import Header          # 用來構造郵件的頭部
from email.mime.application import MIMEApplication   
from email.mime.multipart import MIMEMultipart  # 用來構造附件

# 發送郵件的步驟
# 第一步:建立一個SMTP的對象
s = smtplib.SMTP()
# 第二步:連接配接到SMTP的伺服器
host = 'smtp.163.com'    # 設定163郵箱伺服器,端口為:25
port = 25
#  host = 'smtp.qq.com'    # 設定qq郵箱伺服器,端口為:465
s.connect(host,port)   # 連接配接伺服器
# 第三步:登入SMTP伺服器
mail_user = '[email protected]'     # 163郵箱的使用者名
mail_pass = 'password'               # 注意:此處填寫的是郵箱的SMTP伺服器授權碼
s.login(user=mail_user,password=mail_pass)

# 構造文本郵件内容
content = '使用python測試發送郵件'             # 建構郵件内容
textcontent = MIMEText(content,_charset='utf8')        # _charset 指定編碼格式
# 構造附件(二進制位元組流形式)
part = MIMEApplication(open("report.html",'rb').read(),_subtype=None) 
# part = MIMEApplication(open("report.html",'rb').read()) 需要檢視_subtype=None 是否會引發異常
part.add_header('content-disposition', 'attachment', filename='report18.html')  # 對方收到郵件之後,附件在郵件中顯示的名稱
# 封裝一封郵件
msg = MIMEMultipart()
# 加入文本内容
msg.attach(textcontent)
msg.attach(part)
# 發送郵件
msg['From'] = '[email protected]'       #發件人郵箱
msg['To'] = '[email protected]'             #收件人

#第五步:發送郵件
s.sendmail(from_addr='[email protected]',to_addrs='[email protected]',msg=msg.as_string())      # 将郵件内容轉換為字元串
      

使用python發送郵件時常見錯誤:

錯誤1:smtplib.SMTPAuthenticationError: (550, b'User has no permission')   

我們使用python發送郵件時相當于自定義用戶端根據使用者名和密碼登入,然後使用SMTP服務發送郵件,新注冊的163郵箱是預設不開啟用戶端授權的(對指定的郵箱大師用戶端預設開啟),是以登入總是被拒絕,解決辦法(以163郵箱為例):進入163郵箱-設定-用戶端授權密碼-開啟(授權碼是用于登入第三方郵件用戶端的專用密碼)。上述有專門的設定方法。

錯誤2:smtplib.SMTPAuthenticationError: (535, b'Error: authentication failed')   

以163郵箱為例,在開啟POP3/SMTP服務,并開啟用戶端授權密碼時會設定授權碼,将這個授權碼代替smtplib.SMTP().login(user,password)方法中的password即可。

錯誤3:給多人發送郵件是,可能會出現“AttributeError: 'list' object has no attribute 'encode'”或者寫了多個人,實際隻給第一個人發了郵件等錯誤。

# 将所有的收件人郵箱寫入到一個字元串中
msg['To'] = '[email protected], [email protected], [email protected], [email protected]'
# 發送郵件時,通過字元串函數split分割,分割後傳回的每一個郵箱賬号
s.sendmail(from_addr=msg['From'], to_addrs=msg['To'].split(','), msg=msg.as_string())      

繼續閱讀