2014年10月1日 星期三

Android automatic send e-mail 自動發送e-mail

也就是不需經過使用者即可發送email,是寄件者(開發者)寄送給其他收件者的方法
1.安裝jar檔
mail.jar
activation.jar
additionnal.jar
 將這三個檔案下載到專案的libs資料夾上,接著在eclips重新整理專案,在這三個檔案按右鍵->Bulid Path-> Add to Build Path 完成
 2.在src新增建立資料夾com,在資料夾com裡面再建立一個資料夾provider,接著再eclips裡此資料夾下建立 JSSEProvider.java
 
/*
 *  Licensed to the Apache Software Foundation (ASF) under one or more
 *  contributor license agreements.  See the NOTICE file distributed with
 *  this work for additional information regarding copyright ownership.
 *  The ASF licenses this file to You under the Apache License, Version 2.0
 *  (the "License"); you may not use this file except in compliance with
 *  the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

/**
 * @author Alexander Y. Kleymenov
 * @version $Revision$
 */


import java.security.AccessController;
import java.security.Provider;

public final class JSSEProvider extends Provider {

    public JSSEProvider() {
        super("HarmonyJSSE", 1.0, "Harmony JSSE Provider");
        AccessController.doPrivileged(new java.security.PrivilegedAction() {
            public Void run() {
                put("SSLContext.TLS",
                        "org.apache.harmony.xnet.provider.jsse.SSLContextImpl");
                put("Alg.Alias.SSLContext.TLSv1", "TLS");
                put("KeyManagerFactory.X509",
                        "org.apache.harmony.xnet.provider.jsse.KeyManagerFactoryImpl");
                put("TrustManagerFactory.X509",
                        "org.apache.harmony.xnet.provider.jsse.TrustManagerFactoryImpl");
                return null;
            }
        });
    }
}
3.在自己的專案src資料夾下建立GMailSender.java
import javax.activation.DataHandler;   
import javax.activation.DataSource;   
import javax.mail.Message;   
import javax.mail.PasswordAuthentication;   
import javax.mail.Session;   
import javax.mail.Transport;   
import javax.mail.internet.InternetAddress;   
import javax.mail.internet.MimeMessage;   

import android.util.Log;

import java.io.ByteArrayInputStream;   
import java.io.IOException;   
import java.io.InputStream;   
import java.io.OutputStream;   
import java.security.Security;   
import java.util.Properties;   

public class GMailSender extends javax.mail.Authenticator {   
    private String mailhost = "smtp.gmail.com";   
    private String user;   
    private String password;   
    private Session session;   

    static {   
        Security.addProvider(new com.provider.JSSEProvider());   
    }  

    public GMailSender(String user, String password) {   
        this.user = user;   
        this.password = password;   
        Log.i("user::::::::", user);
        Log.i("password::::::::", password);
        Properties props = new Properties();   
        props.setProperty("mail.transport.protocol", "smtp");   
        props.setProperty("mail.host", mailhost);   
        props.put("mail.smtp.auth", "true");   
        props.put("mail.smtp.port", "465");   
        props.put("mail.smtp.socketFactory.port", "465");   
        props.put("mail.smtp.socketFactory.class",   
                "javax.net.ssl.SSLSocketFactory");   
        props.put("mail.smtp.socketFactory.fallback", "false");   
        props.setProperty("mail.smtp.quitwait", "false");   

        session = Session.getDefaultInstance(props, this);   
    }   

    protected PasswordAuthentication getPasswordAuthentication() {   
        return new PasswordAuthentication(user, password);   
    }   

    public synchronized void sendMail(String subject, String body, String sender, String recipients) throws Exception {   
        try{
          Log.i("subject::::::::", subject);
             Log.i("body::::::::", body);
             Log.i("sender::::::::", sender);
             Log.i("recipients::::::::", recipients);
        MimeMessage message = new MimeMessage(session);   
        DataHandler handler = new DataHandler(new ByteArrayDataSource(body.getBytes(), "text/plain"));   
        message.setSender(new InternetAddress(sender));   
        message.setSubject(subject);   
        message.setDataHandler(handler);  

        /*******2015.09.29 附加圖片*******/
        // create multipart
        Multipart multipart = new MimeMultipart();

        // create bodypart with image and set content-id
        MimeBodyPart messageBodyPart = new MimeBodyPart();
        File testImage = new File("/storage/emulated/0/Download/", "test.png"); //手機檔案位置,檔案名稱
        DataSource source = new FileDataSource(testImage);
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName("image.png");
        messageBodyPart.setDisposition(MimeBodyPart.INLINE);
        messageBodyPart.setHeader("Content-ID","");
        multipart.addBodyPart(messageBodyPart);

        // create bodypart with html content and reference to the content-id
        messageBodyPart = new MimeBodyPart();
        String htmlText = "";
        messageBodyPart.setContent(htmlText, "text/html");
        multipart.addBodyPart(messageBodyPart);

        // add multipart to message
        message.setContent(multipart);
        
        /***************參考來源 http://goo.gl/OAZn5q ****************/

 
        if (recipients.indexOf(',') > 0)   
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients));   
        else  
            message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients));   
        Transport.send(message);   
        }catch(Exception e){
          Log.i("eeeeee::::::::", e+"");
        }
    }   

    public class ByteArrayDataSource implements DataSource {   
        private byte[] data;   
        private String type;   

        public ByteArrayDataSource(byte[] data, String type) {   
            super();   
            this.data = data;   
            this.type = type;   
        }   

        public ByteArrayDataSource(byte[] data) {   
            super();   
            this.data = data;   
        }   

        public void setType(String type) {   
            this.type = type;   
        }   

        public String getContentType() {   
            if (type == null)   
                return "application/octet-stream";   
            else  
                return type;   
        }   

        public InputStream getInputStream() throws IOException {   
            return new ByteArrayInputStream(data);   
        }   

        public String getName() {   
            return "ByteArrayDataSource";   
        }   

        public OutputStream getOutputStream() throws IOException {   
            throw new IOException("Not Supported");   
        }   
    }   
}  
4.接著在想觸發的檔案上加上此段code
try {   
                    GMailSender sender = new GMailSender("username@gmail.com", "password"); //寄件者(開發方)帳號與密碼
                    sender.sendMail("This is Subject",   //信件標題
                            "This is Body",   //信件內容
                            "username@gmail.com",   //寄件者
                            "user@yahoo.com");   //收件者
                } catch (Exception e) {   
                    Log.e("SendMail", e.getMessage(), e);   
                } 
5.可能發生問題在 Log.i("eeeeee::::::::", e+"");
A.android.os.NetworkOnMainThreadExceptionMainActivity.java加上此段
/* 加入StrictMode避免發生 android.os.NetworkOnMainThreadException */
  StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
    .detectDiskReads().detectDiskWrites().detectNetwork()
    .penaltyLog().build());
B.javax.mail.AuthenticationFailedException 此為無法登入帳號,可能是帳號密碼錯誤,或是帳號未設定 此時GMail會收到信,點選連結變更設定
https://www.google.com/settings/security/lesssecureapps

 啟動IMAP
 完成
 參考資料:
http://stackoverflow.com/questions/2020088/sending-email-in-android-using-javamail-api-without-using-the-default-built-in-a/2033124#2033124

http://stackoverflow.com/questions/1334802/how-can-i-use-external-jars-in-an-android-project/6859020#6859020

http://bbs.csdn.net/topics/310000387

http://stackoverflow.com/questions/7398382/embedd-inline-images-using-java-mail-in-android

檔案位置:https://github.com/terryyamg/AutoEmail

12 則留言 :

  1. 大大你好 我照你的做法 跑到 這一行 GMailSender sender = new GMailSender("username@gmail.com", "password"); //寄件者(開發方)帳號與密碼 就會當掉 這是何解 能否幫忙 感恩 !!

    回覆刪除
    回覆
    1. 我有放上檔案位置,可以直接下載import看看

      刪除
  2. 請問一下
    夾帶一張圖片寄出該怎麼做
    請教一下 謝謝

    回覆刪除
    回覆
    1. 在GMailSender.java我有更新附加圖片的程式碼,測試過可以
      記得在AndroidManifest.xml加上" android.permission.WRITE_EXTERNAL_STORAGE "權限。
      參考連結在http://goo.gl/OAZn5q

      刪除
    2. 大大請問我想讓使用者在介面自己設定寄件收件人
      我要怎麼修改程讀取已經存好的使用者資料 而不是到程式碼裡修改 感恩~

      刪除
    3. 哈囉,你可以在使用者介面讓使用者輸入後,
      存在SharedPreferences或SQLite裡面,然後在要送出的時候,
      再取出寄件者帳號密碼與收件人帳號字串,放到對應的位置就好了。

      刪除
  3. 哈囉~我想請問您
    我已經把您的檔案import了
    也有按照上面的步驟
    寄件者(開發方)帳號與密碼也有改成正確的了
    但是信件還是沒有發送成功
    不知道是哪裡出了問題 ˊ_ˋ
    目前很需要這個功能
    請您幫幫我 謝謝~~~

    回覆刪除
    回覆
    1. 啊~我剛剛成功了
      很謝謝你的分享唷 ^^

      刪除
  4. 請問一下目前這個方法在android 5.1 版本有用嗎?

    回覆刪除
  5. 您好 我想請問
    我更改信件標題和信件的內容
    為何收到訊息還是This is Subject和This is Body?

    回覆刪除
    回覆
    1. 基本上是修改
      -----------------------------------
      sender.sendMail("This is Subject", //信件標題
      "This is Body", //信件內容
      "username@gmail.com", //寄件者
      "user@yahoo.com"); //收件者
      -----------------------------------
      這裡就可以了,然後可以看看Log訊息
      -----------------------------------
      Log.i("subject::::::::", subject);
      Log.i("body::::::::", body);
      -----------------------------------
      看訊息是否是您輸入的內容,如果不是可以看看有無error訊息

      刪除