在服务中发送电子邮件(不提示用户) [英] Send Email in Service (without prompting user)

查看:32
本文介绍了在服务中发送电子邮件(不提示用户)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能我在后台使用服务发送电子邮件..就像在服务中我使用带有 ACTION_SENDTO 的 Intent 和 Uri 数据 mailto:recipient_email 并且它在没有任何用户干预的情况下在后台发送..或通过默认的电子邮件应用程序而不提示用户...

is it possible that I send email in background using service.. like in service I use Intent with ACTION_SENDTO with Uri data mailto:recipient_email and it get sent in the background without any user intervention .. or through default email app without prompting the user ...

推荐答案

最好的解决方案是使用 Gmail 帐户发送电子邮件.

The best solution is using the Gmail account to send the email.

一般来说:

  1. 为 android 下载 mail.jar 和 activation.jar https://code.google.com/p/javamail-android/
  2. 连接到 GMail 以获取 OAuth 令牌
  3. 发送电子邮件

这是代码

import java.util.Properties;

import javax.activation.DataHandler;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.URLName;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.util.ByteArrayDataSource;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.AccountManagerCallback;
import android.accounts.AccountManagerFuture;
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;

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

public class GMailSender {
    private Session session;
    private String token;


    public String getToken() {
        return token;
    }

    public GMailSender(Activity ctx) {
        super();
        initToken(ctx);
    }

    public void initToken(Activity ctx) {

        AccountManager am = AccountManager.get(ctx);

        Account[] accounts = am.getAccountsByType("com.google");
        for (Account account : accounts) {
            Log.d("getToken", "account="+account);  
        }

        Account me = accounts[0]; //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, ctx, new AccountManagerCallback<Bundle>(){
            @Override
            public void run(AccountManagerFuture<Bundle> result){
                try{
                    Bundle bundle = result.getResult();
                    token = bundle.getString(AccountManager.KEY_AUTHTOKEN);
                    Log.d("initToken callback", "token="+token);    

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

        Log.d("getToken", "token="+token);
    }



    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;

        /* enable if you use this code on an Activity (just for test) or use the AsyncTask
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
         */

        transport.connect(host, port, userEmail, emptyPassword);

        byte[] response = String.format("user=%s1auth=Bearer %s11",
                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(), e);
        }
    }

}

此代码最初发布在此处Android 中使用 XOauth 的 Javamail api.

this code was originally posted here Javamail api in android using XOauth.

请注意,要获取 OAuth 令牌,您需要一个活动,并且您必须询问用户要使用哪个帐户.应在 OnCreate 阶段检索令牌并保存在首选项中.另请参阅 如何获取 Android 设备的主要电子邮件地址

Please note to get the OAuth token you need an Activity and you have to ask the user which account to use. The token should be retrieved during the OnCreate phase and saved in the preferences. See also How to get the Android device's primary e-mail address

或者,您可以使用 mail.jar,但您必须向用户询问他们的用户名和密码.

Alternatively you can use mail.jar but you have to ask the user for their username and password.

这篇关于在服务中发送电子邮件(不提示用户)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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