上一篇文章中我介紹了使用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出品,正規大廠,質量信得過產品,呵呵。html
核心代碼片斷:
java
// 創建發送郵件任務 new AsyncTask<String, Integer, Boolean>() { @Override protected Boolean doInBackground(String... params) { //使用commons-net中的AuthenticatingSMTPClient AuthenticatingSMTPClient client = new AuthenticatingSMTPClient("TLS", true); try { client.connect("smtp.gmail.com", 465); client.ehlo("localhost"); //須要ehlo一下 client.sendCommand("AUTH XOAUTH2 " + 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( String recipient : recipientsArray ) { client.addRecipient(recipient); } }else { recipientsArray = new String[]{recipients.toString()}; client.addRecipient(recipients.toString()); } //處理郵件主題與正文 Writer writer = client.sendMessageData(); if(null != writer) { //使用apache mime4j中的EncoderUtil來處理中文亂碼的問題 String encodedSubject = EncoderUtil.encodeIfNecessary(subject, Usage.TEXT_TOKEN, 0); //使用apache mime4j中的EncoderUtil來編碼郵件主題 String encodedBody = EncoderUtil.encodeB(body.getBytes()); //使用apache mime4j中的EncoderUtil來編碼郵件正文 Log.i(SMSBroadcastReceiver.class.getName(), "encodedSubject: " + encodedSubject); Log.i(SMSBroadcastReceiver.class.getName(), "encodedBody: " + encodedBody); SimpleSMTPHeader header = new SimpleSMTPHeader(me.name, recipientsArray[0], encodedSubject); header.addHeaderField("Content-Type", "text/plain; charset=UTF-8"); header.addHeaderField("Content-Transfer-Encoding", "base64"); for (int i = 0; i < recipientsArray.length; i++) { if(0 == i) continue; header.addCC(recipientsArray[i]); } writer.write(header.toString()); writer.write(encodedBody); writer.close(); } return true; } catch (Exception e) { return false; } finally { try { client.disconnect(); } catch (IOException e) { } } } }.execute();