python - 如何使用 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()}
我假设,文件的编码是破坏附加的电子表格的原因。任何帮助,将不胜感激。
解决方案
尝试更改这两行:
msg = MIMEBase(main_type, sub_type)
msg.set_payload(fp.read())
仅此:
msg = MIMEApplication(fp.read(), sub_type)
推荐阅读
- java - 带有子查询的Spring数据jpa多表连接
- asp.net-core - ASP.NET Core 中的 TraceId、RequestId 和 TraceIdentifier
- .net - 点网单元测试框架工具,用于在点网源代码上自动生成单元测试方法
- javascript - 模态不使用道具关闭
- matlab - 从命令行调用 Matlab 会遇到未知类型的意外异常,为什么?
- c# - 结合字符串中的日期和时间并转换为日期时间
- r - 将列表列表传递给函数的正确方法,缺少和/或不相关的元素
- rust - 映射数字范围 Rust
- plot - 如何限制以前的情节?
- database - 从 AB BA 中删除重复数据