gpt4 book ai didi

Python gmail api发送带附件pdf的电子邮件全部空白

转载 作者:行者123 更新时间:2023-11-28 16:20:32 24 4
gpt4 key购买 nike

我正在使用 python 3.5,下面的代码主要来自 google api 页面... https://developers.google.com/gmail/api/guides/sending针对 python 3.x 略作修改

我可以成功发送包含内容文本和附件 pdf 的电子邮件,但附件中的 pdf 完全空白..

请帮助并提前致谢

def create_message_with_attachment(bcc, subject, message_text,  file,sender='me' ):
message = MIMEMultipart()
message['bcc'] = bcc
message['from'] = sender
message['subject'] = subject

msg = MIMEText(message_text)
message.attach(msg)

content_type, encoding = mimetypes.guess_type(file)

main_type, sub_type = content_type.split('/', 1)
fp = open(file, 'rb')
msg = MIMEBase(main_type, sub_type)
msg.set_payload(fp.read())
fp.close()
filename = os.path.basename(file)
msg.add_header('Content-Disposition', 'attachment', filename=filename)
message.attach(msg)

raw = base64.urlsafe_b64encode(message.as_bytes())
raw = raw.decode()
return {'raw':raw}

最佳答案

您只是忘记了对附件进行编码。将两行代码替换为:

  import email.encoders

...
msg.add_header('Content-Disposition', 'attachment',filename=filename)
email.encoders.encode_base64(msg)
message.attach(msg)
...

关于Python gmail api发送带附件pdf的电子邮件全部空白,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40583272/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com