我正在使用Google OAuth 2.0代表我的用户使用Gmail发送电子邮件。它使用SMTP协议。这是我的代码:
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());
我们的软件托管在Google App Engine平台上。使用上述方法发送的电子邮件始终具有值为“base64”的Content-Transfer-Encoding标头。
使用gmail.com发送的普通电子邮件不会像这样编码。有办法吗?或者这是一直期待的?所有电子邮件服务提供商(包括私人服务器)都支持它吗?我对此知之甚少。感谢。
答案 0 :(得分:1)
首先,您可以使用built-in OAuth2 support中的JavaMail 1.5.2来简化您对OAuth2的使用。
身份验证方法不会对JavaMail选择的Content-Transfer-Encoding产生任何影响;它完全基于消息的实际内容。如果您的内容包含许多非ASCII字符,则它将使用base64。