首页 > 解决方案 > 如何使用 Python 3.7 将 excel 文件附加到 Gmail?

问题描述

我在 python 3.7 中创建了一个函数来为所有客户创建带有附加电子表格的草稿电子邮件。该代码正确地创建了该电子邮件草稿并附加了文件 (.xlsx),但这些文件无法再在 gmail 上打开。不确定这是否特定于我使用的编码。(这些文件可以在我的台式电脑上成功打开)

下面是代码:

def CreateMessageWithAttachment(sender, to, cc, subject, message_text, file_dir, filename):
    """Create email messages with attachment, for sending to partners"""
    message = MIMEMultipart('alternative')
    message['to'] = to
    message['from'] = sender
    message['cc'] = cc
    message['subject'] = subject
    msg = MIMEText(message_text, 'html')
    message.attach(msg)
    path = os.path.join(file_dir, filename)
    content_type, encoding = mimetypes.guess_type(path)
    if content_type is None or encoding is not None:
        content_type = 'application/octet-stream'

    main_type, sub_type = content_type.split('/', 1)
    #    main_type, sub_type = 'gzip', None
    fp = open(path, 'rb')
    msg = MIMEBase(main_type, sub_type)
    msg.set_payload(fp.read())
    fp.close()
    msg.add_header('Content-Disposition', 'attachment', filename=filename)
    message.attach(msg)
    raw = base64.urlsafe_b64encode(message.as_bytes())
    raw = raw.decode()
    return {'raw': raw}
    #return {'raw': base64.urlsafe_b64encode(message.as_bytes()).decode()}

我假设,文件的编码是破坏附加的电子表格的原因。任何帮助,将不胜感激。

标签: pythonpython-3.xbase64gmail-api

解决方案


尝试更改这两行:

msg = MIMEBase(main_type, sub_type)
msg.set_payload(fp.read())

仅此:

msg = MIMEApplication(fp.read(), sub_type)

推荐阅读