将Google文档转换为PDF并发送带有PDF附件的电子邮件

时间:2019-03-10 12:10:29

标签: python-2.7 google-drive-api gmail

我正在尝试将Google文档转换为PDF(使用Drive API),然后将文件附加到电子邮件(使用Gmail API)。

脚本运行,将Google文档转换为PDF,发送带有附件的电子邮件,但PDF附件为空/损坏。

我怀疑问题出在以下行:msg.set_payload(fh.read())

相关文档:set_payloadio.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()

1 个答案:

答案 0 :(得分:1)

此修改如何?我认为从Google云端硬盘下载文件时,您的脚本是正确的。因此,我建议修改用于发送带有附件文件的电子邮件的脚本。

我认为msg.set_payload(fh.read())是您所说的修改点之一。因此,getvalue()检索了email.encoders.encode_base64()检索到的数据。而且我还修改了message_obj

修改后的脚本:

请进行如下修改。

发件人:

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()

收件人:

from email import encoders  # Please add this.

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.getvalue())  # Modified
encoders.encode_base64(msg)  # Added

msg.add_header('Content-Disposition', 'attachment', filename='an example file name.pdf')
message.attach(msg)

message_obj = {'raw': base64.urlsafe_b64encode(message.as_bytes()).decode()}  # Modified

service.users().messages().send(userId="me", body=message_obj).execute()

注意:

  • 此修改假设您已经能够使用Gmail API发送电子邮件。如果您无法使用Gmail API,请确认范围以及是否在API控制台上启用了Gmail API。

在我的环境中,我可以确认修改后的脚本有效。但是,如果这在您的环境中不起作用,我深表歉意。