在android中使用OAuth发送电子邮件而无需用户交互
我在尝试连接到smtp时遇到此错误在android中使用OAuth发送电子邮件而无需用户交互,android,oauth,smtp,Android,Oauth,Smtp,我在尝试连接到smtp时遇到此错误 javax.mail.MessagingException: 334 eyJzdGF0dXMiOiI0MDAiLCJzY2hlbWVzIjoiQmVhcmVyIiwic2NvcGUiOiJodHRwczovL21haWwuZ29vZ2xlLmNvbS8ifQ== 这是我的密码 public class GMailOauthSender { private Session session; public SMTPTransport conne
javax.mail.MessagingException: 334 eyJzdGF0dXMiOiI0MDAiLCJzY2hlbWVzIjoiQmVhcmVyIiwic2NvcGUiOiJodHRwczovL21haWwuZ29vZ2xlLmNvbS8ifQ==
这是我的密码
public class GMailOauthSender
{
private Session session;
public SMTPTransport connectToSmtp(String host, int port, String userEmail, String oauthToken, boolean debug) throws Exception {
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.getInstance(props);
session.setDebug(debug);
final URLName unusedUrlName = null;
SMTPTransport transport = new SMTPTransport(session, unusedUrlName);
// If the password is non-null, SMTP tries to do AUTH LOGIN.
final String emptyPassword = null;
transport.connect(host, port, userEmail, emptyPassword);
byte[] response = String.format("user=%s\1auth=Bearer %s\1\1", userEmail, oauthToken).getBytes();
response = BASE64EncoderStream.encode(response);
transport.issueCommand("AUTH XOAUTH2 " + new String(response), 235);
return transport;
}
public synchronized void sendMail(String subject, String body, String user, String oauthToken, String recipients) {
try {
SMTPTransport smtpTransport = connectToSmtp("smtp.gmail.com",587,user,oauthToken,true);
MimeMessage message = new MimeMessage(session);
DataHandler handler = new DataHandler(new ByteArrayDataSource(body.getBytes(), "text/plain"));
message.setSender(new InternetAddress(user));
message.setSubject(subject);
message.setDataHandler(handler);
if (recipients.indexOf(',') > 0)
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients));
else
message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients));
smtpTransport.sendMessage(message, message.getAllRecipients());
} catch (Exception e) {
Log.d("test", e.getMessage());
}
}
}
我从堆栈溢出的某个地方得到了这段代码。
任何帮助???您收到的错误
eyJzdGF0dXMiOiI0MDAiLCJzY2hlbWVzIjoiQmVhcmVyIiwic2NvcGUiOiJodHRwczovL21haWwuZ29vZ2xlLmNvbS8ifQ==
使用Base64解码器解码到以下内容
{"status":"400","schemes":"Bearer","scope":"https://mail.google.com/"}
这最终意味着(与消息一样神秘)您正在使用的身份验证令牌已过期。您需要使它失效,然后获得一个新的(只需再次请求令牌)
您可以如下方式使令牌无效:
mAccountManager.invalidateAuthToken("con.google", mAuthenticationToken);
我希望这是有帮助的:)试试这个,它可能会对你有所帮助。让我知道,即使你有任何问题。嗨,哈什穆克谢谢你的答复。这很好,但我想从用户已经在手机中设置的帐户发送电子邮件。在这种情况下,我如何在这里获取密码?这意味着谷歌播放Ac,在手机中设置Ac时使用密码?是的,完全正确。不,对不起,亲爱的,甚至让我们试着用另一种方式为你找到答案。