2. python發送郵件並帶附件報異常:TypeError: Invalid application MIME subtype

1. python發送郵件代碼如下

# -*-coding:utf8-*-
"""
=========================================
author: Lujier           time: 2019/7/1
E-mail: [email protected]
==========================================
"""

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

"""
該模塊的郵件發送包含附件
"""
# 創建一個stmp對象
s = smtplib.SMTP()

# 連接到SMTP服務器
host = "smtp.163.com"  # 注意163郵箱的smtp用的是25端口,qq用的是465端口
s.connect(host, 25)

# 登錄SMTP服務器
mail_account = '[email protected]'  # 發件郵箱
mail_pwd = '*******'  # 授權碼
s.login(user=mail_account, password=mail_pwd)

# 構建一封郵件
mail_content = MIMEMultipart()

# 構建郵件內容
Subject = '2019/07/01郵件發送'  # 郵件主題
mail_content['Subject'] = Header(Subject, 'utf8')
From = mail_account
To = '[email protected]'
mail_content['From'] = From  # 發件人
mail_content['To'] = To  # 收件人

content = MIMEText('測試郵件是否發送成功')  # 郵件正文
mail_content.attach(content)

# 構建附件
# 1. 附件路徑
filepath = r"""D:\APP_Workplaces\AutoTest_Learn\requests_tests02\request20190624\reports\20190628093654TestReport.html"""

fileObj = MIMEApplication(open(filepath, 'rb').read(), _subtype=None)

fileObj.add_header('content-disposition', 'attachment', filename='report.html')

# 郵件添加附件
mail_content.attach(fileObj)

# 發送郵件
s.sendmail(from_addr=From, to_addrs=To, msg=mail_content.as_string())

2.  結果運行報如下截圖錯誤:

Traceback (most recent call last):
  File "D:/App_Workplaces/AutoTest_Learn/AutoTest_Learn/requeststest_02/homework/web_service_20190701/send_email_file.py", line 49, in <module>
    fileObj = MIMEApplication(open(filepath, 'rb').read(), _subtype=None)
  File "D:\APP_Installs\python3.7\lib\email\mime\application.py", line 33, in __init__
    raise TypeError('Invalid application MIME subtype')
TypeError: Invalid application MIME subtype

3.  問題分析:

 通過報錯信息我們進入源碼application模塊中,並定位在application模塊 __init__中,init中代碼如下:

 def __init__(self, _data, _subtype='octet-stream',
                 _encoder=encoders.encode_base64, *, policy=None, **_params):
        """Create an application/* type MIME document.

        _data is a string containing the raw application data.

        _subtype is the MIME content type subtype, defaulting to
        'octet-stream'.

        _encoder is a function which will perform the actual encoding for
        transport of the application data, defaulting to base64 encoding.

        Any additional keyword arguments are passed to the base class
        constructor, which turns them into parameters on the Content-Type
        header.
        """
        if _subtype is None:
            raise TypeError('Invalid application MIME subtype')
        MIMENonMultipart.__init__(self, 'application', _subtype, policy=policy,
                                  **_params)
        self.set_payload(_data)
        _encoder(self)

對比異常信息,TypeError: Invalid application MIME subtype,那我們就知道,是因爲_subtype is None,所以拋出異常,未走

MIMENonMultipart.__init__(self, 'application', _subtype, policy=policy , **_params)

這時候,我們就知道了原因了:   是我們在創建   MIMEApplication 對象時,參數  _subtype is None

 

4. 解決方法:

   在我們自己發送郵件的代碼中,修改一行代碼: 

fileObj = MIMEApplication(open(filepath, 'rb').read(), _subtype=False)

當然: _subtype也可以是其他,不一定非要是False

這時候,郵件就可以發送成功了

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章