'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'] = "[email protected]"
        message['cc'] = "[email protected]"
        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



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source