Search code examples
apicurlgmail-api

400 Recipient address required, when I called the API gmail with curl


I want to use :

curl --request POST \
'https://gmail.googleapis.com/gmail/v1/users/me/messages/send?key=[YOUR_API_KEY]' \ --header 'Authorization: Bearer [YOUR_ACCESS_TOKEN]' \ --header 'Accept: application/json' \ --header 'Content-Type: application/json' \ --data '{"raw":"","payload":{"partId":"","headers":[{"name":"MIME-Version","value":"1.0"},{"name":"Subject","value":"Subject test"},{"name":"From","value":"email1@gmail.com"},{"name":"To","value":"email2@gmail.com, email3@gmail.com"}]}}' \ --compressed

But I always have error like :

{ "error": { "code": 400, "message": "Recipient address required", "errors": [ { "message": "Recipient address required", "domain": "global", "reason": "invalidArgument" } ], "status": "INVALID_ARGUMENT" } }

I use Gmail for Developers > Gmail API to test it: https://developers.google.com/gmail/api/reference/rest/v1/users.messages/send

  1. GET https://gmail.googleapis.com/gmail/v1/users/{userId}/messages/{id} => work well
  2. GET https://gmail.googleapis.com/gmail/v1/users/{userId}/messages => work well
  3. POST https://gmail.googleapis.com/gmail/v1/users/{userId}/messages/send => KO

Do you have any idea why this error?


Solution

  • You had to base64 encode the raw content of the email so it allows to send the email. You can use this online encoder to generate the email and then encode it and submit it to the raw parameter, the parameters in your example should be like:

    From: test@gmail.com,
    To: test2@gmail.com,
    Subject:Gmail API test
    Content-type: text/html;charset=iso-8859-1,
    
    This is a test.
    

    Once encoded you just need to add the result in the raw parameter like:

    curl --request POST \
      'https://gmail.googleapis.com/gmail/v1/users/me/messages/send?key=[YOUR_API_KEY]' \
      --header 'Authorization: Bearer [YOUR_ACCESS_TOKEN]' \
      --header 'Accept: application/json' \
      --header 'Content-Type: application/json' \
      --data '{"raw":"RnJvbTogdGVzdEBnbWFpbC5jb20sCiAgICBUbzogdGVzdDJAZ21haWwuY29tLAogICAgU3ViamVjdDpHbWFpbCBBUEkgdGVzdAogICAgQ29udGVudC10eXBlOiB0ZXh0L2h0bWw7Y2hhcnNldD1pc28tODg1OS0xLAoKICAgIFRoaXMgaXMgYSB0ZXN0IHBsZWFzZSB3b3JrLg=="}' \
      --compressed
    

    Then it will result in the email being sent.