sendgrid-python: HTTP Error 400: Bad Request on - sendgrid (6.0.5)
Issue Summary
Using the basic template for 6.05 I’m getting 400 bad request error.\
Steps to Reproduce
- Run pip install
sudo pip3 install sendgrid
- Run script
import os
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail
from urllib.request import HTTPError
import python_http_client
to_emails = [
("ian@example.com", 'Ian One'),
("ian2@example.com", 'Ian Two')
]
message = Mail(
from_email=('no-reply@example.com', 'Example 01'),
to_emails=to_emails,
subject='Email Alert',
html_content='<strong>and easy to do anywhere, even with Python</strong>')
print(message.get())
try:
sendgrid_client = SendGridAPIClient(os.environ.get('RD_OPTION_SENDGRID_API_KEY'))
response = sendgrid_client.send(message)
print(response.status_code)
print(response.body)
print(response.headers)
except (HTTPError, python_http_client.exceptions.BadRequestsError) as error:
print(error)
Response = HTTP Error 400: Bad Request
Output of message.get()
{
"from": { "name": "Example 01", "email": "no-reply@example.com" },
"personalizations": [
{
"to": [
{ "name": "Ian One", "email": "ian@example.com" },
{ "name": "Ian Two", "email": "ian2@example.com" }
]
}
],
"subject": "Email Alert",
"content": [
{
"value": "<strong>and easy to do anywhere, even with Python</strong>",
"type": "text/html"
}
]
}
Technical details:
- sendgrid-python Version: sendgrid (6.0.5)
- Python Version: 3.5
I’m a bit baffled how the basic template fails to send here?
About this issue
- Original URL
- State: closed
- Created 7 years ago
- Reactions: 8
- Comments: 20 (5 by maintainers)
Do note that often there are additional details about the error in the response body. Example how to catch and log/print send failures:
The 400 Bad Request error is an HTTP status code indicates that the request you sent to the webserver was malformed , in other words, the data stream sent by the client to the server didn’t follow the rules. It means that the request itself has somehow incorrect or corrupted and the server couldn’t understand it. There are a number of different causes for a 400: Bad Request Error . It might be a malformed request syntax, invalid request message framing, or deceptive request routing . In most cases, the problem is on the website itself, and there’s not much you can do about that.
I encountered 400 Error when trying to send to multiple recipients in BCC. Found the resolution here: https://sendgrid.com/docs/API_Reference/Web_API_v3/Mail/errors.html Hope it helps.
Another observation is if you just try to send with Subject only (aka empty body). It responds with Http 404 Bad Request, too.