Python3-EmailMessage-Excel文件附件变为ATT00001.xlsx

时间:2019-05-14 16:53:10

标签: python-3.x

我正在尝试发送带有Excel工作表(.xlsx)作为附件的电子邮件。当文件名超过65个字符时,附件将变成ATT00001.xlsx并损坏。有没有办法可以解决这个问题而又不限制文件名中的字符数?

下面是我的代码,任何建议都会有帮助。

import os
import smtplib
import email
import mimetypes #For guessing MIME type based on file name extension
import logging
from email.message import EmailMessage
from email.mime.text import MIMEText # for adding email body

def email_report(test_res, body_summ, report_file, table, recipients):
    """
    Email Report
    :param test_res: Test Result
    :param body_summ: Email body text
    :param report_file: Report file that needs to be attached 
    :param table: Table name for which test happened 
    :param recipients: Email recipients 
    :return: None
    """
    # Create the message
    msg = EmailMessage()

    msg['Subject'] = "Regression Test Result - %s - %s" % (table, test_res)
    msg['To'] = recipients
    msg['From'] = email.utils.formataddr(('Test', 'xyz@abc.com'))

    body_int = "Hi,\n\nPlease find Test Summary below\n\n"      
    body_sig ="\nFor more details refer attached excel."    

    # find attachment type and add to email    
    ctype, encoding = mimetypes.guess_type(report_file)
    filename=os.path.basename(report_file)
    if ctype is None or encoding is not None:
        ctype = 'application/octet-stream'
    maintype, subtype = ctype.split('/', 1)
    with open(report_file, 'rb') as fp:
        msg.add_attachment(fp.read(),
                            maintype=maintype,
                            subtype=subtype,
                            filename=filename)
    # add email body
    msg.attach(MIMEText(body_int + body_summ + body_sig, 'plain'))

    # Now send
    with smtplib.SMTP('localhost') as s:
         s.send_message(msg)
    logging.info("Email sent to {}".format(recipients))

1 个答案:

答案 0 :(得分:0)

它与您的代码无关,而与Exchange服务器格式化电子邮件的方式更多。

如果您尝试发送包含文本和附件部分的消息,则会发生这种情况。 Microsoft Exchange将附件后的所有内容解释为附件。也许尝试在正文之后添加附件。


来源: