Python gmail api send email with attachment pdf all blank
Asked Answered
P

2

7

I am using python 3.5 and below code is mostly from the google api page... https://developers.google.com/gmail/api/guides/sending slightly revised for python 3.x

i could successfully send out the email with the content text and an attachment pdf but the pdf attached is completely blank..

please help and thanks in advance

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}
Precedence answered 14/11, 2016 at 6:49 Comment(1)
What did you expect it to show?Convenance
R
11

you just forgot to encode the attachment. Replace two lines of your code with those:

  import email.encoders

  ...
  msg.add_header('Content-Disposition', 'attachment',filename=filename)
  email.encoders.encode_base64(msg)
  message.attach(msg)
  ...
Ruthannruthanne answered 9/9, 2017 at 7:56 Comment(1)
Thanks for your help. Small tip: import email.encoder makes some conflict. like: AttributeError: 'str' object has no attribute 'encoders'. Even there is no variable like email around. So, I solved the point like import email.encoders as encoder than 2nd line : encoder.encode_base64(msg) solved.Toiletry
G
0

Less line of code, Seem to work well, but very slow :

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)

But I don't know what append with maintype, this argument is needed, and you can write whatever you want it will works, I didn't find actually any documentation on it.Don't manage SMTP enough to know it otherwise. If anyone know...

Grogshop answered 10/6, 2018 at 18:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.