从 Google Drive 附加文件

1 投票
2 回答
1022 浏览
提问于 2025-04-18 01:41

我一直在尝试用Jinja2创建一个模板化的Google Drive文档,并最终将这个文档作为PDF附件发送邮件。

到目前为止,我已经完成了大部分工作,但现在在附件部分遇到了问题。我收到一个错误信息,内容是"InvalidAttachmentTypeError: Invalid attachment type"

另外,有没有办法让这个过程更高效一些呢?

class Upload(webapp2.RequestHandler):
  @decorator.oauth_required
  def get(self):
    if decorator.has_credentials():
      try:
          body = {'title': 'My New Text Document',
                  'description': 'Hello World'}

          template = JINJA_ENVIRONMENT.get_template('document.html')
          template_values = {'name': 'Simon'}
          fh = StringIO.StringIO(template.render(template_values))

          media_body = MediaIoBaseUpload(fh,
                                         mimetype='text/html',
                                         resumable=False)

          http = httplib2.Http(memcache)
          http = decorator.http()

          service = discovery.build('drive', 'v2', http=http)

          file = service.files().insert(body=body,
                                        media_body=media_body,
                                        convert=True).execute(http=http)

          m = mail.EmailMessage()
          m.sender = 'myfromemailaaddress@gmail.com'
          m.to = 'mytoemailaddress@gmail.com'
          m.subject = 'My Subject'
          m.html = '<p>My body.</p>'
          m.attachments = [(file['title'],
                            file['exportLinks']['application/pdf'])]
          m.send()

          self.redirect('/')

        except client.AccessTokenRefreshError:
          self.redirect('/')

    else:
      self.redirect(decorator.authorize_url())

2 个回答

1

在m.attachments这个属性里,你应该像现在这样为每个附件准备一个元组,第一个元素是文档的标题,第二个元素是文档的内容。

在你的情况下,你的文档内容只是一个字符串,并不是一个文件,这就是你遇到的问题。你应该先从云端硬盘获取PDF文件,然后再把它作为附件添加上。

你可以查看这里,了解如何使用downloadURL属性(或者在你的情况下使用exportLinks)来下载文件内容。

另外,请确保你的文件有正确的扩展名。没有扩展名或者某些特定扩展名的文件是被禁止的,无法作为附件发送。查看这个

希望这些信息对你有帮助。

1

经过很多次尝试,我终于搞明白了怎么做。现在把这个分享给和我有相同困扰的人。

class Upload(webapp2.RequestHandler):
@decorator.oauth_required
def get(self):
  if decorator.has_credentials():
    try:
      body = {'title': 'My New Text Document',
              'description': 'Hello World'}

      template = JINJA_ENVIRONMENT.get_template('document.html')
      template_values = {'name': 'Simon'}
      fh = StringIO.StringIO(template.render(template_values))

      media_body = MediaIoBaseUpload(fh,
                                     mimetype='text/html',
                                     resumable=False)

      http = httplib2.Http(memcache)
      http = decorator.http()

      service = discovery.build('drive', 'v2', http=http)

      file = service.files().insert(body=body,
                                    media_body=media_body,
                                    convert=True).execute(http=http)

      download_url = file['exportLinks']['application/pdf']
      resp, content = service._http.request(download_url)

      m = mail.EmailMessage()
      m.sender = 'myfromemailaaddress@gmail.com'
      m.to = 'mytoemailaddress@gmail.com'
      m.subject = 'My Subject'
      m.html = '<p>My body.</p>'
      m.attachments = [('myfile.pdf', str(content))]
      m.send()

      self.redirect('/')

    except client.AccessTokenRefreshError:
      self.redirect('/')

  else:
    self.redirect(decorator.authorize_url())

撰写回答