Search code examples
pythongmail-api

How to attach Encrypted PDF to gmail's attachment using python


I have this block of code that will attach a file to gmail. it works fine with other file type but when dealing with "encrypted pdf" (but the file can be viewed normally or MANUALLY attach to gmail without entering password) the 'pdf' attachment in gmail that was added by this function requires password to view. Does anyone know how to fix ? I do not have the password for the file because it is just a that my boss want to send to customer for information.

   def create_message_with_attachment():
        message = MIMEMultipart()
        message = MIMEText(message_data, "plain")     
        message.attach(message )
        
        
        message['to'] = "test@gmail.com"
        message['cc'] = "cc@gmail.com"
        message['subject'] = "testing sub"
        file= "test.pdf" # this file is encrypted, can view and print and edit the text box 
        just_fun = True        
        #BEGIN attach files to attachment of the email
        id= 1 #just to be used in cid 
        if just_fun:      
          content_type, encoding = mimetypes.guess_type(file)

          if content_type is None or encoding is not None:
               content_type = 'application/octet-stream'

               main_type, sub_type = content_type.split('/', 1)

               if main_type == 'text':
                   fp = open(file, 'rb')
                   msg = MIMEText(fp.read().decode("utf-8"), _subtype=sub_type)
                   fp.close()
               elif main_type == 'image':
                   fp = open(file, 'rb')
                   msg = MIMEImage(fp.read(), _subtype=sub_type)
                   fp.close()
               elif main_type == 'audio':
                    fp = open(file, 'rb')
                    msg = MIMEAudio(fp.read(), _subtype=sub_type)
                    fp.close()
               elif main_type == "pdf":
                    fp = open(file, 'rb')
                    msg = MIMEApplication(fp.read(), _subtype = sub_type)
               else:
                    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_message = base64.urlsafe_b64encode(message.as_string().encode("utf-8"))
        return {'raw': raw_message.decode("utf-8")}

here is the image example of the output of the above code . the encrypted PDF is attached and sent but will ask password when open. enter image description here

Thanks for reading


Solution

  • I have found a solution from a post about pdf display empty after the attach process. so below is the answer for my own problem. .

    def create_message_with_attachment():
            message = MIMEMultipart()
            message = MIMEText(message_data, "plain")     
            message.attach(message )
            message['to'] = "test@gmail.com"
            message['cc'] = "cc@gmail.com"
            message['subject'] = "testing sub"
            file= "test.pdf" # this file is encrypted, can view and print and edit the text box 
            just_fun = True        
            #BEGIN attach files to attachment of the email
            id= 1 #just to be used in cid 
            if just_fun:      
              content_type, encoding = mimetypes.guess_type(file)
              if content_type is None or encoding is not None:
                   content_type = 'application/octet-stream'
                   main_type, sub_type = content_type.split('/', 1)
                   if main_type == 'text':
                       fp = open(file, 'rb')
                       msg = MIMEText(fp.read().decode("utf-8"), _subtype=sub_type)
                       fp.close()
                   elif main_type == 'image':
                       fp = open(file, 'rb')
                       msg = MIMEImage(fp.read(), _subtype=sub_type)
                       fp.close()
                   elif main_type == 'audio':
                        fp = open(file, 'rb')
                        msg = MIMEAudio(fp.read(), _subtype=sub_type)
                        fp.close()
                   elif main_type == "pdf":
                        fp = open(file, 'rb')
                        msg = MIMEApplication(fp.read(), _subtype = sub_type)
                   else:
                        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)
                   #need to encode the pdf here before attach
                   import email.encoders #import this one to encode
                   email.encoders.encode_base64(msg)
                   # now can attach the pdf file to the message
                   message.attach(msg)
            raw_message = base64.urlsafe_b64encode(message.as_string().encode("utf-8"))
            return {'raw': raw_message.decode("utf-8")}             
    

    Answer referenced from https://stackoverflow.com/a/46128450/14134982 by @Tomek Jurkiewicz