我在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()}
我认为,文件的编码是损坏所附电子表格的原因。任何帮助将不胜感激。
答案 0 :(得分:0)
尝试更改这两行:
msg = MIMEBase(main_type, sub_type)
msg.set_payload(fp.read())
要这样:
msg = MIMEApplication(fp.read(), sub_type)