Gmail API HTML message with UTF-8 character-set extended characters

Just converted my GCP cloud Java app to send email messages to Google Workspace via Gmail API rather than sendmail. In the past I was able to format HTML UTF-8 and send extended characters, but now google is replacing them with "?" literals once it receives the message. I have verified that prior to sending using Gmail API the characters are there, and verified that after the message is sent through Gmail and distributed to the client, the raw message text contains "?" instead of the original characters.

In my HTML message body I am using this meta tag:

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>

The special characters include the alternative form for double-open quotes, double-close quotes, and stylized apostrophe:

<p>โ€œMustโ€™ve been fate, you and I.โ€</p>

Gmail API is replacing this with:

<p>?Must?ve been fate, you and I.?</p>

and it shows that way on all devices/mail clients because the "?" are now literal.

Java code that calls the Gmail API:

MimeMessage email = new MimeMessage(session);
...

email.setSubject(subject);
email.setContent(htmlBodyText, "text/html");
...
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
email.writeTo(buffer);
byte[] rawMessageBytes = buffer.toByteArray();
String encodedEmail = Base64.encodeBase64URLSafeString(rawMessageBytes);
Message message = new Message();
message.setRaw(encodedEmail);
...
message = service.users().messages().send(myEmailAddress, message).execute();

Suggestions?

 

Solved Solved
0 2 731
1 ACCEPTED SOLUTION

Hi @dev-admin-43217 ,

It looks like the issue is with Javaโ€™s MimeMessage handling the encoding, not the Gmail API itself.

Try this in your code before sending:
email.setSubject(subject, "UTF-8");
email.setContent(htmlBodyText, "text/html; charset=UTF-8");
Also, when you create the MimeMessage, set the session like this:
Properties props = new Properties();
props.put("mail.mime.charset", "UTF-8");
Session session = Session.getInstance(props);
MimeMessage email = new MimeMessage(session);




View solution in original post

2 REPLIES 2

Hi @dev-admin-43217 ,

It looks like the issue is with Javaโ€™s MimeMessage handling the encoding, not the Gmail API itself.

Try this in your code before sending:
email.setSubject(subject, "UTF-8");
email.setContent(htmlBodyText, "text/html; charset=UTF-8");
Also, when you create the MimeMessage, set the session like this:
Properties props = new Properties();
props.put("mail.mime.charset", "UTF-8");
Session session = Session.getInstance(props);
MimeMessage email = new MimeMessage(session);




That did it!  Thank you so much!