【发布时间】:2019-11-17 18:46:54
【问题描述】:
我目前正在从事一个项目,我需要向用户发送邮件并附加一些来自 Google Docs 的文档。
我有要发送的文件的文件 ID。我不想下载文件然后将其附加到邮件中。有没有办法直接从谷歌驱动器附加文件而不将它们下载到我们的本地存储?
我尝试过的方法-
我首先尝试导出文件,然后将类似字节的对象存储在变量中,然后将其传递给 create_message() 方法。但是 mimeType.guess_type() 需要一个类似字符串的对象,它可以是路径或 url。
然后我尝试将驱动器url直接传递给create_message()方法但没有成功。
这是我的 create_message 方法 -
def create_message_with_attachment(self, sender, to, subject, message_text,files):
"""Create a message for an email.
Args:
sender: Email address of the sender.
to: Email address of the receiver.
subject: The subject of the email message.
message_text: The text of the email message.
file: The path to the file to be attached.
Returns:
An object containing a base64url encoded email object.
"""
message = MIMEMultipart()
message['to'] = to
message['from'] = sender
message['subject'] = subject
msg = MIMEText(message_text)
message.attach(msg)
for fil in files:
content_type, encoding = mimetypes.guess_type(fil)
if content_type is None or encoding is not None:
content_type = 'application/octet-stream'
main_type, sub_type = content_type.split('/', 1)
if main_type == 'text':
fp = open(fil, 'rb')
msg = MIMEText(fp.read(), _subtype=sub_type)
fp.close()
elif main_type == 'image':
fp = open(fil, 'rb')
msg = MIMEImage(fp.read(), _subtype=sub_type)
fp.close()
elif main_type == 'audio':
fp = open(fil, 'rb')
msg = MIMEAudio(fp.read(), _subtype=sub_type)
fp.close()
else:
fp = open(fil, 'rb')
msg = MIMEBase(main_type, sub_type)
msg.set_payload(fp.read())
fp.close()
filename = os.path.basename(fil)
msg.add_header('Content-Disposition', 'attachment', filename=filename)
message.attach(msg)
b64_bytes = base64.urlsafe_b64encode(message.as_bytes())
b64_string = b64_bytes.decode()
body = {'raw': b64_string}
return body
files 参数是数组,因为我想在 3-4 左右发送多个附件。
到目前为止还没有运气。谁能建议其他方法来实现这一点?
【问题讨论】:
标签: python google-drive-api gmail-api google-docs-api google-api-python-client