Python Sendgrid send email with PDF attachment file

后端 未结 3 2013

I\'m trying to attach a PDF file to my email sent with sendgrid.

Here is my code :

sg = sendgrid.SendGridAPIClient(apikey=os.environ.get(\'SENDGRID_A         


        
3条回答
  •  一个人的身影
    2021-01-12 01:25

    This is my solution, Works with Sendgrid V3

        # Where it was uploaded Path.
        file_path = "MY_FILE_PATH"
    
        with open(file_path, 'rb') as f:
            data = f.read()
    
        # Encode contents of file as Base 64
        encoded = base64.b64encode(data).decode()
    
        """Build attachment"""
        attachment = Attachment()
        attachment.content = encoded
        attachment.type = "application/pdf"
        attachment.filename = "my_pdf_attachment.pdf"
        attachment.disposition = "attachment"
        attachment.content_id = "PDF Document file"
    
        sg = sendgrid.SendGridAPIClient(apikey=settings.SENDGRID_API_KEY)
    
        from_email = Email("origin@gmail.com")
        to_email = Email('recipient@gmail.com')
        content = Content("text/html", html_content)
    
        mail = Mail(from_email, 'Attachment mail PDF', to_email, content)
        mail.add_attachment(attachment)
    
        try:
            response = sg.client.mail.send.post(request_body=mail.get())
        except urllib.HTTPError as e:
            print(e.read())
            exit()
    

提交回复
热议问题