How to fix up sendgrid-python, BadRequestsError

Traceback (most recent call last):
  File "sendmail.py", line 79, in <module>
    response = sg.client.mail.send.post(request_body=mail.get())
  File "/home/errong_leng/.local/lib/python2.7/site-packages/python_http_client/client.py", line 227, in http_request
    return Response(self._make_request(opener, request))
  File "/home/errong_leng/.local/lib/python2.7/site-packages/python_http_client/client.py", line 161, in _make_request
    raise exc
python_http_client.exceptions.BadRequestsError

The easy way is to catch this exception and print out the error body:
try:
    response = sg.client.mail.send.post(request_body=mail.get())
    print(response.status_code)
    print(response.body)
    print(response.headers)
except Exception as e:
    print (e.body)  #print (e.read()) 


Then you can know why bad request error reported, such as:
{"errors":[{"message":"Following RFC 1341, section 7.2, if either text/html or text/plain are to be sent in your email: text/plain needs to be first, followed by text/html, followed by any other content.","field":"content","help":null}]}

{"errors":[{"message":"The subject is required. You can get around this requirement if you use a template with a subject defined or if every personalization has a subject defined.","field":"subject","help":"http://sendgrid.com/docs/API_Reference/Web_API_v3/Mail/errors.html#message.subject"}]}

{"errors":[{"message":"Each email address in the personalization block should be unique between to, cc, and bcc. We found the first duplicate instance of [errong.leng@gmail.com] in the personalizations.0.to field.","field":"personalizations.0","help":"http://sendgrid.com/docs/API_Reference/Web_API_v3/Mail/errors.html#message.recipient-errors"}]}

Comments

Popular posts from this blog

How to fix error : no module named sendgrid when try to use sendgrid python lib in PHP.

react-native run-android : sun.security.provider.cert path.SunCertPathBuilderException : unable to find valid certification path to req uested target

react-native run-android : do not build/update modified code(App.js)