Draft Email Creation with Gmail API in ASP.NET WebForms Without Libraries

While using the Gmail API in an ASP.NET WebForms project, my draft emails are created empty. Below is a modified example:

string endpointUrl = "https://gmail.googleapis.com/upload/gmail/v1/users/" + userEmail + "/drafts?access_token=" + tokenStr;
string emailText = "From: " + senderField.Text + "\nTo: " + receiverField.Text + "\nSubject: " + subjectField.Text + "\n\n" + bodyField.Text;
string jsonData = "{\"message\":{\"raw\":\"" + ConvertToSafeBase64(emailText) + "\"}}";

using (var httpClient = new HttpClient())
{
    var data = new StringContent(jsonData, Encoding.UTF8, "message/rfc822");
    var httpResponse = httpClient.PostAsync(endpointUrl, data).Result;
    var responseData = httpResponse.Content.ReadAsStringAsync().Result;
    // Process response to extract draft ID if needed
}

public static string ConvertToSafeBase64(string input)
{
    byte[] bytes = Encoding.UTF8.GetBytes(input);
    return Convert.ToBase64String(bytes).Replace('+', '-').Replace('/', '_').Replace("=", "");
}

Looking for any advice on resolving the empty draft issue.

Based on my experience, the issue might be related to the Content-Type header in the HTTP request. I once encountered a similar problem where the draft was not created correctly because the Gmail API was expecting JSON formatted data instead of the message/rfc822 type. Changing the media type to application/json helped resolve the issue. Additionally, verifying the output of the base64 conversion to ensure it produces a properly formatted string was crucial. Checking the API’s expected data format in the documentation can provide further guidance on how to structure the request.