如何在消息中附加 Google 驱动器文件并通过 gmail API 发送(无需下载文件)?

How to attach a Google Drive file in message and send through gmail API (without downloading the file)?

我目前正在开展一个项目,我需要向用户发送邮件并附加 Google 文档中的一些文档。

我有要发送的文档的文件 ID。我不想下载文件然后将其附加到邮件中。有什么方法可以直接从 google 驱动器附加文件而无需将它们下载到我们的本地存储?

我试过的方法-

  1. 我首先尝试导出文件,然后将类似字节的对象存储在变量中,然后将其传递给create_message() 方法。但是 mimeType.guess_type() 需要一个类似字符串的对象,它可以是路径或 url.

  2. 然后我尝试直接将驱动器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

文件参数是数组,因为我想在 3-4 左右发送多个附件。

到目前为止还没有运气。任何人都可以建议其他方法来实现这一目标吗?

Google 应用程序的问题是您无法在下载或导出它们时保留数据类型 - 它们需要转换为不同的 MIMEType。因此,如果您在发送带有附件的 e-mails 时遇到问题,我建议您执行以下解决方法: 在您的 e-mail 文件中包含一个 link,而不是文件本身。在这种情况下,您必须执行以下步骤:

与各自的用户共享感兴趣的文件。您可以通过创建和更新 permissions 以编程方式执行此操作。在您的情况下,您需要指定 emailAddress、文件 ID,并在请求正文中包含您要赋予电子邮件收件人的角色。如果您更新现有权限,您还需要指定 permissionId。 包含 webViewLink of the desired file in your email body. You can obtain the webViewLink by listing files 并将 webViewLink 指定为您要在响应中获取的字段