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

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

问题描述

我有可能在后台使用服务发送电子邮件。像在服务我使用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令牌

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

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

帐号me = accounts [0]; //您需要在设备上获取一个Google帐户,如果您有多个


am.getAuthToken(我,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异常{

属性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);
//如果密码不为空,SMTP尝试执行AUTH LOGIN。
final String emptyPassword = null;

/ *启用,如果您在活动(仅用于测试)上使用此代码或使用AsyncTask
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()。permitAll()。建立();
StrictMode.setThreadPolicy(policy);
* /

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

byte [] response = String.format(user =%s\1auth =承载%s\1\1,
userEmail,oauthToken).getBytes();
response = BASE64EncoderStream.encode(response);

transport.issueCommand(AUTH XOAUTH2+ new String(response),235);

返回运输;
}

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(recipient));
smtpTransport.sendMessage(message,message.getAllRecipients());

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

}

最初发布在这里使用XOauth的android中的Javamail api



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



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


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 ...

解决方案

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

Generally speaking:

  1. download mail.jar and activation.jar for android https://code.google.com/p/javamail-android/
  2. Connect to GMail to get the OAuth token
  3. Send the email

here's the code

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

}

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

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

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

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

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