从 Google Drive 附加文件
我一直在尝试用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
经过很多次尝试,我终于搞明白了怎么做。现在把这个分享给和我有相同困扰的人。
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())