2016-11-17 37 views
3

sendgridで送信された電子メールにPDFファイルを添付しようとしています。Python SendgridがPDF添付ファイル付きのメールを送信

sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY')) 

from_email = Email("[email protected]") 
subject = "subject" 
to_email = Email("[email protected]") 
content = Content("text/html", email_body) 

pdf = open(pdf_path, "rb").read().encode("base64") 
attachment = Attachment() 
attachment.set_content(pdf) 
attachment.set_type("application/pdf") 
attachment.set_filename("test.pdf") 
attachment.set_disposition("attachment") 
attachment.set_content_id(number) 

mail = Mail(from_email, subject, to_email, content) 
mail.add_attachment(attachment) 

response = sg.client.mail.send.post(request_body=mail.get()) 

print(response.status_code) 
print(response.body) 
print(response.headers) 

しかしSendgrid PythonライブラリがエラーHTTPエラー400を投げている:不正な要求を

は、ここに私のコードです。

私のコードで何が問題になっていますか?

+0

で動作要求がhttps://sendgrid.com/docs/を使用してvlidされている場合、あなたがチェックできますClassroom/Send/v3_Mail_Send/sandbox_mode.html – WannaBeCoder

+0

問題はベースラインの周りにあると思います。ここにコンテンツを設定すると、https://github.com/sendgrid/sendgrid-python/blob/ca96c8dcd66224e13b38ab8fd2d2b429dd07dd02/examples/helpers/mail/mail_example.py#L66のようなコンテンツが設定されます。しかし私がbase64でコード化された私のPDFファイルを使用しているときに私はエラー – John

答えて

6

解決策が見つかりました。今、それが動作

with open(pdf_path,'rb') as f: 
    data = f.read() 
    f.close() 

encoded = base64.b64encode(data) 

:これにより

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

:私はこの行を置き換えます。私はset_contentでエンコードされたファイルを送信することができます

attachment.set_content(encoded) 
+1

を得ました。 'with'文を終了するときにファイルが閉じられているので、' f.close() 'は必要ありません。 – elgehelge

1

これが私の解決策である、Sendgrid V3

with open(file_path, 'rb') as f: 
     data = f.read() 
     f.close() 
    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("[email protected]") 
    to_email = Email('[email protected]') 
    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() 
関連する問題