Python Sendgrid send email with PDF attachment file

后端 未结 3 2012

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条回答
  •  猫巷女王i
    2021-01-12 01:15

    I found a solution. I replaced this line :

    pdf = open(pdf_path, "rb").read().encode("base64")
    

    By this :

    with open(pdf_path, 'rb') as f:
        data = f.read()
    
    encoded = base64.b64encode(data)
    

    Now it works. I can send encoded file in the set_content :

    attachment.set_content(encoded)
    

    Note: The answer above works for Sendgrid v2 or lower. For v3 and up use:

    encoded = base64.b64encode(data).decode()
    

提交回复
热议问题