android - 在服务中发送电子邮件(不提示用户)

标签 android email service android-intent

我是否有可能在后台使用服务发送电子邮件……就像在服务中一样,我将 Intent 与 ACTION_SENDTO 和 Uri 数据 mailto:recipient_email 一起使用,它会在后台发送而无需任何用户干预……或通过默认电子邮件应用程序发送而不提示用户...

最佳答案

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

一般来说:

  1. 下载 mail.jar 和 activation.jar for android https://code.google.com/p/javamail-android/
  2. 连接到 GMail 以获取 OAuth token
  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=%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(), e);
        }
    }

}

此代码最初发布于此处 Javamail api in android using XOauth .

请注意,要获取 OAuth token ,您需要一个 Activity ,并且您必须询问用户要使用哪个帐户。应在 OnCreate 阶段检索 token 并保存在首选项中。另见 How to get the Android device's primary e-mail address

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

关于android - 在服务中发送电子邮件(不提示用户),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6517079/

相关文章:

Laravel 8 : Connection could not be established with host smtp. gmail.com

spring-mvc - Spring Boot RestController,关于错误状态响应体,错误消息为空

android - 如何在Android中设置进度条的最大值

android - 如何为字符串数组的 XML 字符串创建 java POJO?

html - schema.org 的电子邮件属性可以使用 href 值吗?

python - 在 python 中找不到文件作为附件发送

service - ZF2 通过附加参数从服务管理器获取服务

java - REST Web 应用程序 : what is the role of XML/JSON?

java - Android onClick() 任务全部同时发生

java - Android/Java - ListView 使用 ArrayList 填充 XML 数据 : Only Displays First Item