I am using Google OAuth 2.0 to send emails on behalf of my users using Gmail. It uses the SMTP protocol. Here is my code:
Properties props = new Properties();
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.starttls.required", "true");
props.put("mail.smtp.sasl.enable", "false");
Session session = Session.getInstance(props);
session.setDebug(false);
final URLName unusedUrlName = null;
SMTPTransport transport = new SMTPTransport(session, unusedUrlName);
transport.connect("smtp.gmail.com", 587, fromAddress, null);
byte[] response = String.format("user=%s\1auth=Bearer %s\1\1", lFrom, oauthToken).getBytes();
response = BASE64EncoderStream.encode(response);
transport.issueCommand("AUTH XOAUTH2 " + new String(response),
235);
MimeMessage msg = new MimeMessage( session );
msg.setFrom( new InternetAddress( fromAddress , fromName ) );
msg.setRecipients( Message.RecipientType.TO , InternetAddress.parse( toAddress , false ) );
msg.setSubject( emailSubject );
MimeBodyPart htmlPart = new MimeBodyPart();
Multipart multiPart = new MimeMultipart();
htmlPart.setContent( "<html>email content</html>" , "text/html; charset=UTF-8" );
multiPart.addBodyPart( htmlPart );
msg.setContent( multiPart );
msg.saveChanges();
transport.sendMessage(msg, msg.getAllRecipients());
Our software is hosted on the Google App Engine platform. The emails sent using the above method always have Content-Transfer-Encoding header with value "base64".
Normal emails sent using gmail.com aren't encoded like this. Is there a way around? Or is this what is always expected? Do all email service providers (including private servers) support it? I know very little about this. Thanks.
First of all, you can simplify your use of OAuth2 by using the built-in OAuth2 support in JavaMail 1.5.2.
The authentication method isn't going to have any effect on the Content-Transfer-Encoding that JavaMail chooses; it's based entirely on the actual content of the message. If your content includes a lot of non-ASCII characters, it will use base64.