我正在尝试使用javax.mail和Google OAuth发送电子邮件。我的工作流程是:
用户使用Google OAuth登录,获取access_token,将令牌发送到java后端服务器,然后使用javax.mail通过电子邮件进行身份验证和发送电子邮件。令牌,而不是电子邮件&密码。但是,在我在道具中设置令牌后,我仍然收到无效的用户名和密码错误。你有任何想法如何解决它?
Properties props = new Properties();
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.starttls.required", "true");
props.put("mail.smtp.sasl.enable", "true");
props.put("mail.smtp.sasl.mechanisms", "XOAUTH2");
props.put("mail.smtp.auth", "false");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
props.put("mail.imaps.auth.login.disable", "true");
props.put("mail.imaps.auth.plain.disable", "true");
props.put(OAuth2SaslClientFactory.OAUTH_TOKEN_PROP, accessToken);
Session session = Session.getInstance(props);
session.setDebug(true);
MimeMessage mimeMessage = new MimeMessage(session);
mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(toEmail));
mimeMessage.setSubject("test");
mimeMessage.setContent("xxx", "text/html");
SMTPTransport transport = (SMTPTransport)session.getTransport("smtp");
transport.connect("smtp.gmail.com", myEmailAddress, "");
transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
transport.close();