def compose_message(body, subject, contacts): """ composes message using message text, subject, contacts and returns it encoded """ message = MIMEMultipart() message['subject'] = subject message['from'] = me message['to'] = contacts plaintext_body = html_to_text(body) print("Plaintext:\n%s" % (plaintext_body)) message.attach(MIMEText(plaintext_body, "plain")) # Attach the pdf to the msg going by e-mail pdf = load_foia_pdf(body) if pdf: attach = MIMEApplication(pdf, _subtype="pdf") # attach = MIMEApplication(f.read(),_subtype="pdf") attach.add_header('Content-Disposition', 'attachment', filename="records-request.pdf") message.attach(attach) # python2 try: return {'raw': base64.urlsafe_b64encode(message.as_string())} # python 3 except TypeError: enc_bytes = base64.urlsafe_b64encode(message.as_bytes()) return {'raw': enc_bytes.decode("utf-8")}