1


我正在通过 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)

这段代码有什么问题?

4

2 回答 2

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());
于 2013-09-13T08:03:57.413 回答
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();
   }
}
于 2016-02-02T08:08:50.990 回答