2016-11-17 2 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 파이썬 라이브러리 오류 HTTP 오류 400을 던지고있다 : 잘못된 요청을

여기 내 코드입니다.

내 코드가 잘못되었습니다.

+0

을 확인할 수 Sendgrid V3와 함께 작동 https://sendgrid.com/docs/ Classroom/Send/v3_Mail_Send/sandbox_mode.html – WannaBeCoder

+0

문제는 base64 줄 주변에 있다고 생각합니다. 여기에 콘텐츠를 설정하면 https://github.com/sendgrid/sendgrid-python/blob/ca96c8dcd66224e13b38ab8fd2d2b429dd07dd02/examples/helpers/mail/mail_example.py#L66 작동합니다. 그러나 base64로 인코딩 된 PDF 파일을 사용할 때 – John

답변

6

해결책을 찾았습니다. 이로써

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

:

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

encoded = base64.b64encode(data) 

지금 작동 나는이 줄을 교체했다. 나는 set_content에서 인코딩 된 파일을 보낼 수 있습니다 : 이것은 내 솔루션입니다

attachment.set_content(encoded) 
+1

오류가 발생합니다. 'with' 문을 종료 할 때 파일이 닫혀 있기 때문에'f.close()'할 필요가 없습니다. – elgehelge

1

, 요청이 사용 vlid 경우

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() 
관련 문제