【问题标题】:Send Email using JavaMail And OAuth使用 JavaMail 和 OAuth 发送电子邮件
【发布时间】:2014-10-02 10:47:15
【问题描述】:

我需要使用带有 OAuth 的 javamail API 通过我的应用程序发送电子邮件 但我需要如何使用我在下面添加的代码。

我的代码:

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());
    }
}
}

【问题讨论】:

    标签: android jakarta-mail google-oauth


    【解决方案1】:

    你为什么不使用JavaMail's built in OAuth support而不是使用它?

    【讨论】:

      猜你喜欢
      • 2014-07-26
      • 1970-01-01
      • 2015-08-19
      • 2018-12-18
      • 2015-04-22
      • 2012-04-27
      • 2017-10-17
      • 2019-08-10
      相关资源
      最近更新 更多