【发布时间】:2019-03-11 06:56:49
【问题描述】:
我正在尝试将 Google Doc 转换为 PDF(使用 Drive API),然后将文件附加到电子邮件中(使用 Gmail API)。
脚本运行,将 Google Doc 转换为 PDF,发送带有附件的电子邮件,但 PDF 附件为空白/损坏。
我怀疑问题出在以下行:msg.set_payload(fh.read())
相关文档:set_payload和io.Bytes()
非常感谢任何指导。
import base64
import io
from apiclient.http import MediaIoBaseDownload
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
fileId = '1234'
content_type = 'application/pdf'
response = drive.files().export_media(fileId=fileId, mimeType=content_type)
fh = io.BytesIO()
downloader = MediaIoBaseDownload(fh, response)
done = False
while done is False:
status, done = downloader.next_chunk()
logging.info("Download %d%%." % int(status.progress() * 100))
message = MIMEMultipart()
message['to'] = 'myemail@gmail.com'
message['from'] = 'myemail@gmail.com'
message['subject'] = 'test subject'
msg = MIMEText('test body')
message.attach(msg)
main_type, sub_type = content_type.split('/', 1)
msg = MIMEBase(main_type, sub_type)
msg.set_payload(fh.read()) # i suspect the issue is here
msg.add_header('Content-Disposition', 'attachment', filename='an example file name.pdf')
message.attach(msg)
message_obj = {'raw': base64.urlsafe_b64encode(message.as_string())}
service.users().messages().send(userId="me", body=message_obj).execute()
【问题讨论】:
标签: python-2.7 google-drive-api gmail