使用XOAUTH JavaMail API的android系统 [英] Javamail api in android using XOauth

查看:128
本文介绍了使用XOAUTH JavaMail API的android系统的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要通过我的应用程序使用说发邮件的 JavaMail API的(任何其它邮件服务,如果有也会做)。问题是我不想询问用户他用户名密码

I need to send an email through my app using say the javamail API (any other mailing service if available will also do). the problem is i do not want to ask the user his username and password.

1)是否有可能使用的OAuth 2.0 的JavaMail API /任何其他邮件API

1) Is it possible to use OAuth 2.0 with JavaMail API/ any other mail api

2)如何让OAuth的令牌?

2) how to get OAuth Token ??

3)是否有样本$ C $可在C网

3) Is there a sample code available on the net

在此先感谢。

PS:我从来没有合作过的邮件服务/ SMTP请求

PS: I have never ever worked with mailing services/SMTP requests.

推荐答案

我研究了一段日子,我发现这是为我工作,目前的解决方案。 我得到从Android的AccountManager的oauth2令牌,然后使用JavaMail通过SMTP发送电子邮件。这个想法是基于此<一个Java示例href="http://$c$c.google.com/p/google-mail-oauth2-tools/wiki/JavaSample$c$c">http://$c$c.google.com/p/google-mail-oauth2-tools/wiki/JavaSample$c$c并在此Java XOAUTH这里例如<一href="http://google-mail-xoauth-tools.google$c$c.com/svn/trunk/java/com/google/$c$c/samples/xoauth/XoauthAuthenticator.java">http://google-mail-xoauth-tools.google$c$c.com/svn/trunk/java/com/google/$c$c/samples/xoauth/XoauthAuthenticator.java

I researched this for some days and I found a solution that is working for me at the moment. I get the oauth2 token from the android AccountManager and then send the email via SMTP using JavaMail. The idea is based on the Java example here http://code.google.com/p/google-mail-oauth2-tools/wiki/JavaSampleCode and on this java Xoauth example here http://google-mail-xoauth-tools.googlecode.com/svn/trunk/java/com/google/code/samples/xoauth/XoauthAuthenticator.java

有没有在JavaMail的没有工作的SASL实现Android和使用asmack是行不通的,所以我没有使用SASL,我发出的命令一样,直接在上面的例子XOAUTH

There's no working SASL implementation in JavaMail for Android and using asmack wasn't working so I didn't use SASL and I issued the command directly like in the Xoauth example above.

我得到这样的acount管理器的标记

I get the token from the acount manager like this

AccountManager am = AccountManager.get(this);
Account me = ...; //You need to get a google account on the device, it changes if you have more than one
am.getAuthToken(me, "oauth2:https://mail.google.com/", null, this, new OnTokenAcquired(), null);

private class OnTokenAcquired implements AccountManagerCallback<Bundle>{
    @Override
    public void run(AccountManagerFuture<Bundle> result){
        try{
            Bundle bundle = result.getResult();
            token = bundle.getString(AccountManager.KEY_AUTHTOKEN);

        } catch (Exception e){
            Log.d("test", e.getMessage());
        }
    }
}

如果一切正常,你有记号的oauth2令牌。我用的令牌在这个code

If it works, you have an oauth2 token in token. I use the token in this code

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.Provider;
import java.security.Security;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.URLName;
import javax.mail.Message;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import android.util.Log;

import com.sun.mail.smtp.SMTPTransport;
import com.sun.mail.util.BASE64EncoderStream;

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

}

我不是在这一切的专家,我没有使用任何安全提供如上面的例子,不知道如何会影响到这一点,但它为我工作。 希望这有助于那有人能告诉我,如果有什么问题这一点:P 这是我第一次在这里的回答很抱歉,如果我做错了什么!

I'm not at all an expert in this and I didn't use any Security provider like in the examples above, not sure how it will affect this but it's working for me. Hope this helps and that someone can tell me if there's something wrong with this too :p It's my first answer here so sorry if I did something wrong!

行动,忘了我用一些其他的文件:<一href="https://developers.google.com/google-apps/gmail/xoauth2_protocol">https://developers.google.com/google-apps/gmail/xoauth2_protocol和<一href="http://developer.android.com/training/id-auth/authenticate.html">http://developer.android.com/training/id-auth/authenticate.html

Ops, forgot some other documentation I used: https://developers.google.com/google-apps/gmail/xoauth2_protocol and http://developer.android.com/training/id-auth/authenticate.html

再次OPS!您也可以在清单中需要这些权限

ops again! You also need these permissions in the manifest

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.USE_CREDENTIALS" />

这篇关于使用XOAUTH JavaMail API的android系统的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆