上一篇文章中我介绍了使用Javamail-android在android中发送后台邮件的方法,但是,这个Javamail-android并不是一个靠谱的开源组织发布的,而且是修改过的Javaee,总觉得用起来别扭,所以我就一直搜寻一种更靠谱的解决方案。总算功夫不负有心人,看到了这两篇文章:Sending email without user interaction in Android,Sending a mail in Java (and Android) with Apache Commons Net SMTP : STARTTLS, SSL,在这两篇文章中介绍了使用apache commons-net来发送邮件的方法。这个就很对路了,apache出品,正规大厂,质量信得过产品,呵呵。

核心代码片段:

//建立发送邮件任务newAsyncTask<String,Integer,Boolean>(){@OverrideprotectedBooleandoInBackground(String...params){//使用commons-net中的AuthenticatingSMTPClientAuthenticatingSMTPClientclient=newAuthenticatingSMTPClient("TLS",true);try{client.connect("smtp.gmail.com",465);client.ehlo("localhost");//需要ehlo一下client.sendCommand("AUTHXOAUTH2"+Base64.encodeBase64URLSafeString(String.format("user=%s\1auth=Bearer%s\1\1",me.name,oauthToken).getBytes()));//发送Google的XOAUTH2命令client.setSender(me.name);//处理多个收件人String[]recipientsArray=null;if(recipients.toString().contains(",")){recipientsArray=recipients.toString().trim().split(",");for(Stringrecipient:recipientsArray){client.addRecipient(recipient);}}else{recipientsArray=newString[]{recipients.toString()};client.addRecipient(recipients.toString());}//处理邮件主题与正文Writerwriter=client.sendMessageData();if(null!=writer){//使用apachemime4j中的EncoderUtil来处理中文乱码的问题StringencodedSubject=EncoderUtil.encodeIfNecessary(subject,Usage.TEXT_TOKEN,0);//使用apachemime4j中的EncoderUtil来编码邮件主题StringencodedBody=EncoderUtil.encodeB(body.getBytes());//使用apachemime4j中的EncoderUtil来编码邮件正文Log.i(SMSBroadcastReceiver.class.getName(),"encodedSubject:"+encodedSubject);Log.i(SMSBroadcastReceiver.class.getName(),"encodedBody:"+encodedBody);SimpleSMTPHeaderheader=newSimpleSMTPHeader(me.name,recipientsArray[0],encodedSubject);header.addHeaderField("Content-Type","text/plain;charset=UTF-8");header.addHeaderField("Content-Transfer-Encoding","base64");for(inti=0;i<recipientsArray.length;i++){if(0==i)continue;header.addCC(recipientsArray[i]);}writer.write(header.toString());writer.write(encodedBody);writer.close();}returntrue;}catch(Exceptione){returnfalse;}finally{try{client.disconnect();}catch(IOExceptione){}}}}.execute();


更多相关文章

  1. Android程序界面主题切换
  2. android集成友盟推送,点击通知,先启动应用,然后再跳指定 界面;应用前
  3. Android(安卓)中点击两次返回键才退出
  4. ADB 自制万用驱动方法,解决找不到驱动问题,独家秘笈
  5. Android(14) ArrayAdapter(数组适配器)的三种方法
  6. 详解Android的服务
  7. Android中实现Native与H5的通信方案汇总
  8. Ubuntu 下不能识别android设备的解决方法
  9. eclipse 上调试android的自带应用方法 一

随机推荐

  1. LottieAnimationView 使用无法显示效果
  2. android单稿
  3. android 配置
  4. Maven uploadArchives命令报错:Could not
  5. Android 蓝牙开发常用UUID表
  6. android 布局 ListView中的列表 Relative
  7. android XML shape 使用
  8. Android BLE ERROR CODE
  9. Snackbar
  10. Drawer实现左右侧滑DrawerLayout