如何使用 Python 3.7 将 excel 文件附加到 Gmail?
How to attach excel files to Gmail using Python 3.7?
我在 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)
我在 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)