在android中使用oauth2的Gmail

时间:2016-10-03 14:15:57

标签: java android gmail google-oauth2

我想创建一个应用程序,使用oauth 2在gmail上发送邮件。我关注OAuth2 Support java mail,但app无法运行。我来自OAuth 2.0 Playground。谢谢。

Properties props = new Properties();
props.put("mail.imap.ssl.enable", "true");
props.put("mail.imap.auth.mechanisms", "XOAUTH2");
session = Session.getInstance(props);
session.setDebug(true);
try {
    store = session.getStore("imap");
    store.connect("imap.gmail.com", "pysyren@gmail.com", "access token here");
} catch (NoSuchProviderException e) {
    e.printStackTrace();
} catch (MessagingException e) {
    e.printStackTrace();
}

RetreiveFeedTask task = new RetreiveFeedTask();
task.execute();



class RetreiveFeedTask extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... params) {

        try{
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress("pysyren@gmail.com"));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("vckhanh2310@gmail.com"));
            message.setSubject("Test");
            message.setContent("android", "text/html; charset=utf-8");
            Transport.send(message);
            Toast.makeText(getApplicationContext(), "Dangsend", Toast.LENGTH_LONG).show();
        } catch(MessagingException e) {
            e.printStackTrace();
        } catch(Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        pdialog.dismiss();

        Toast.makeText(getApplicationContext(), "Message sent", Toast.LENGTH_LONG).show();
    }

0 个答案:

没有答案