我正在尝试将Google文档转换为PDF(使用Drive API),然后将文件附加到电子邮件中(使用Gmail API)。
该脚本运行,将Google文档转换为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'] = '[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()
这个修改怎么样?我认为关于从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()
在我的环境中,我可以确认修改后的脚本是否有效。但如果这在你的环境中不起作用,我道歉。