繁体   English   中英

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

[英]Python gmail api send email with attachment pdf all blank

我正在使用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)
  ...

减少代码行,似乎运行良好,但速度很慢:

def SendPDF(to, file, Server):
    msg = EmailMessage()
    msg['From'] = ME
    msg['To'] = to
    msg['Subject'] = 'Send a pdf File'

    with open(file, 'rb') as PDFFile:
        PdfContent = PDFFile.read()

        msg.add_attachment(PdfContent, maintype='', subtype='pdf',
                           filename="The Pdf File Bro.pdf")
    Server.send_message(msg)

但我不知道什么附加maintype,这个论点是必需的,你可以写任何你想要它会工作的东西,我没有找到任何实际的文档。不管管理SMTP,否则不知道它。 如果有人知道......

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM