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

问题描述 投票:1回答:1

我正在尝试将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'] = '[email protected]'
message['from'] = '[email protected]'
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-sdk gmail
1个回答
1
投票

这个修改怎么样?我认为关于从Google云端硬盘下载,您的脚本是正确的。因此,我建议修改脚本以发送带附件文件的电子邮件。

我认为msg.set_payload(fh.read())是你所说的修改点之一。所以getvalue()检索到的数据是由email.encoders.encode_base64()转换的。而且我修改了message_obj

修改后的脚本

请修改如下。

From:

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

To:

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。

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

© www.soinside.com 2019 - 2024. All rights reserved.