Search code examples
delphigmail-api

Gmail API Send email from Delphi client


I am trying to send an email from my Delphi client through gmail with OAUTH2.

I had no problem getting the access token and the refresh token but I cannot send an email.

I created the following JSON and stored it to a TJSONObject called MessageObject.

{
    "payload":
    {
        "headers":[
        {
            "To":"[email protected]"
        }]
    },
    "raw":"A Base64 encoding of the email with RFC 2822 format"
}

I also tries with the below JSON:

{
    "raw":"A Base64 encoding of the email with RFC 2822 format"
}

I use the code below to send the request:

SetLength(HTTPHeader, 2);
HTTPHeader[0] := TNetHeader.Create('Content-Type', 'message/rfc822');
HTTPHeader[1] := TNetHeader.Create('Authorization', 'Bearer ' + sToken);

HTTPClient := THTTPClient.Create;
HTTPResponse := HTTPClient.Post('https://gmail.googleapis.com/upload/gmail/v1/users/me/messages/send',
                                TStringStream.Create(MessageObject.ToJSON), nil, HTTPHeader);

Any ideas what I am doing wrong?


Solution

  • The problem in my code is that I used the wrong endpoint. The one I used is for uploading attachments and does not take a JSON as a body of the POST request.

    The correct one is gmail.googleapis.com/gmail/v1/users/me/messages/send with a Content-Type of application/json.