gmail通过oauth SMTPSendFailedException(需要验证)

时间:2013-09-12 23:10:32

标签: android oauth smtp gmail


我正在通过android上的o-auth应用程序制作gmail。

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.sasl.mechanisms.oauth2.oauthToken", oAuthToken);
Session session = Session.getInstance(props);
SMTPTransport transport = new SMTPTransport(session, null);
transport.connect("smtp.gmail.com", 587, "send-addr@gmail.com", null);

Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress("send-addr@gmail.com"));
msg.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("dest-addr@example.com"));
msg.setSubject("test");
msg.setText("hi!");
transport.sendMessage(message, InternetAddress.parse("send-addr@gmail.com"));

这段代码,[transport.connect(..)成功了,但是[transport.sendMessage(..)失败了。

com.sun.mail.smtp.SMTPSendFailedException: 530-5.5.1 Authentication Required. Learn more at
530 5.5.1 http://support.google.com/mail/bin/answer.py?answer=14257 in2sm6968052pbc.37 - gsmtp
at com.sun.mail.smtp.SMTPTransport.issueSendCommand(SMTPTransport.java:1515)
at com.sun.mail.smtp.SMTPTransport.mailFrom(SMTPTransport.java:1054)
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:634)

这段代码出了什么问题?

2 个答案:

答案 0 :(得分:1)

我修好了这个问题 我用[gmail api python sample]作为参考。

在[transport.sendMessage(...]

之前添加此代码
byte[] bAuth = String.format("user=%s\1auth=Bearer %s\1\1",
                    "send-addr@gmail.com", oAuthToken).getBytes();
String authStr = new String(BASE64EncoderStream.encode(bAuth));

transport.issueCommand("AUTH XOAUTH2 " + authStr, 235);
transport.sendMessage(message, message.getAllRecipients());

答案 1 :(得分:1)

public synchronized void sendMail(final String subject, final String body, final String sender, final String recipients,SMTPTransport transport) throws Exception {
   try
   {
    final MimeMessage message = new MimeMessage(session);
    final DataHandler handler = new DataHandler(new ByteArrayDataSource(body.getBytes(), "text/plain"));
       message.setFrom(new InternetAddress(sender));
       message.setSentDate(new Date());
       message.setSubject(subject);

       message.setDataHandler(handler);
       message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients));


    byte[] bAuth = String.format("user=%s\1auth=Bearer %s\1\1",
            email, oauthToken).getBytes();
    String authStr = new String(BASE64EncoderStream.encode(bAuth));

    transport.issueCommand("AUTH XOAUTH2 " + authStr, 235);
    transport.sendMessage(message,message.getAllRecipients());
     }catch (Exception e) {
       e.printStackTrace();
   }
}