rokkonet

PC・Androidソフトウェア・アプリの開発・使い方に関するメモ

JavaMailによるgmailメール送信サンプル Android開発

2020 May 23.


SendMailTask.java

package YOUR.PACKAGE.PROJECT;
/*
 * 2020 May  23.
 * Ryuichi Hashimoto.
 */

import android.os.AsyncTask;
import java.io.UnsupportedEncodingException;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;
import javax.mail.util.ByteArrayDataSource;

public class SendMailTask extends AsyncTask<Void, Void, Integer> {
    private String senderAddress;
    private String mailPassword;
    private String mailRecipients;
    private String mailSubject;
    private String mailBodyText;
    private String attachFileName;
    private byte[] attachByteArray;
    private Listener listener;

    /*
     * constructor
        senderAddress; 送信元アドレス
        mailPassword; gmailパスワード
        mailSubject; メールタイトル
        mailRecipients; メール受信者アドレス(複数はカンマ区切り)
        mailBodyText; メール本文
        attachByteArray; 添付ファイルのバイト配列
        attachFileName; 添付ファイル名
     */
    SendMailTask(String senderAddress, String mailPassword, String mailRecipients, String mailSubject,
                 String mailBodyText, byte[] attachByteArray, String attachFileName) {
                 // format of Sting-variable-mailRecipients: aaa,bbb,ccc,...

        this.senderAddress = senderAddress;
        this.mailPassword = mailPassword;
        this.mailSubject = mailSubject;
        this.mailRecipients = mailRecipients;
        this.mailBodyText = mailBodyText;
        this.attachByteArray = attachByteArray;
        this.attachFileName = attachFileName;
    }

    protected Integer doInBackground(Void... params) {
        return sendMail(senderAddress, mailPassword, mailRecipients, mailSubject, mailBodyText,
                attachByteArray, attachFileName);
    }


    @Override
    protected void onPostExecute(Integer resultNum) {
        if (listener != null) {
            listener.onSuccess(resultNum);
        }
    }


    /*
     * send mail with javaMail
     *   return
     *     0: succeeded
     *     1: failed to get instance of InternetAddress[]
     *     2: failed to MimeBodyPart#setFileName()
     *     3: MessagingException - failed to send mail
     */
    private int sendMail(final String senderAddress, final String mailPassword,
                         String mailRecipients, final String mailSubject,
                         final String mailBodyText, final byte[] attachByteArray,
                         final String attachFileName) {
            // format of String-variable-mailRecipients: aaa,bbb,ccc,...

        /*
         * set e-mail-recipients to InternetAddress[]
         */
        // convert mailRecipients-string to toAddresses-string-array
        mailRecipients = mailRecipients.replace(",", " ");
        mailRecipients = mailRecipients.trim();
        mailRecipients = mailRecipients.replaceAll(" +", " ");
        String[] toAddresses = mailRecipients.split(" ");
        InternetAddress[] inetToAddress = new InternetAddress[toAddresses.length];
        try {
            for (int i = 0; i < toAddresses.length; i++) {
                inetToAddress[i] = new InternetAddress(toAddresses[i]);
            }
        } catch ( AddressException e) {
            return 1;
        }

        // sending mail with javaMail
        try {
            // set property of javaMail for gmail
            final Properties property = new Properties();
            property.put("mail.smtp.host",                "smtp.gmail.com");
            property.put("mail.host",                     "smtp.gmail.com");
            property.put("mail.smtp.port",                "465");
            property.put("mail.smtp.socketFactory.port",  "465");
            property.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");

            // 認証してセッションを取得
            final Session session = Session.getInstance(property, new javax.mail.Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(senderAddress, mailPassword);
                }
            });

            // set mail-subject, mail-sender, mail-recipients to MimeMessage
            MimeMessage mimeMsg = new MimeMessage(session);
            mimeMsg.setSubject(mailSubject, "utf-8");
            mimeMsg.setFrom(new InternetAddress(senderAddress));
            for(int i = 0; i < inetToAddress.length; i++){
                mimeMsg.addRecipient(javax.mail.Message.RecipientType.TO, inetToAddress[i]);
            }

            /*
             * メール本文と添付ファイルをセット
             */
            // メール本文・添付ファイルを構成する
            final MimeBodyPart txtPart = new MimeBodyPart();
            txtPart.setText(mailBodyText, "utf-8");

            final MimeBodyPart filePart = new MimeBodyPart();
            filePart.setDataHandler(new DataHandler( new ByteArrayDataSource(attachByteArray,
                    "image/jpeg")));
            try {
                filePart.setFileName(MimeUtility.encodeWord(attachFileName));
            } catch (UnsupportedEncodingException e) {
                return 2;
            }

            final Multipart mp = new MimeMultipart();
            mp.addBodyPart(txtPart);
            mp.addBodyPart(filePart); //添付ファイルする場合
            mimeMsg.setContent(mp);

            // メール送信する。
            final Transport transport = session.getTransport("smtp");
            transport.connect(senderAddress,mailPassword);
            transport.sendMessage(mimeMsg, mimeMsg.getAllRecipients());
            transport.close();
            return 0;
        } catch (MessagingException e) {
            return 3;
        }
    }

    void setListener(Listener listener) {
        this.listener = listener;
    }

    interface Listener {
        void onSuccess(int resultNum);
    }
}


MainJavaMail.java

    protected void sendMail() {
        String mailSender = "SENDER@gmail.com";
        String mailPassword = "GMAILPASSWORD";
        String mailRecipients = "RECIPIENT1@SOME.COM,RECIPIENT2@HOO.COM,RECIPIENT3@BAR.COM");
        String mailSubject = "Mail-Title";
        String mailBodyText = "1st line of mail-body" + "\n" + "2nd line of mail-body";
        String attachedFileName = "fileName";

        byte[] byteArrayOfFile;
        /* ここに添付するファイルのbyte[]型byteArrayOfFileを取得するコードを記述する */

        SendMailTask sendMailTask = new SendMailTask( mailSender, mailPassword,
                mailRecipients, mailSubject, mailBodyText, byteArraySmallImage,
                attachedFileName);
                // format of mailRecipients: aaa,bbb,ccc,...

        sendMailTask.setListener(createSendMailListener());
        sendMailTask.execute();
    }


    /*
     *  SendMailTask.Listenerインターフェースの実装
     */
    private SendMailTask.Listener createSendMailListener() {
        return new SendMailTask.Listener() {

            /*
             * SendMailTask終了後に実行するコード
             */
            @Override
            public void onSuccess(int resultNum) {
                Toast toast;
                switch (resultNum) {
                    case 0:
                        toast = Toast.makeText( thisActivity , "Sent Email", Toast.LENGTH_SHORT);
                        toast.show();
                        break;
                    case 1:
                        toast = Toast.makeText(thisActivity,
                                "failed to get instance of InternetAddress[]", Toast.LENGTH_LONG);
                        toast.show();
                        break;
                    case 2:
                        toast = Toast.makeText(thisActivity,
                                "failed to MimeBodyPart#setFileName()", Toast.LENGTH_LONG);
                        toast.show();
                        break;
                    case 3:
                        toast = Toast.makeText(thisActivity,
                                "MessagingException - failed to send mail", Toast.LENGTH_LONG);
                        toast.show();
                        break;
                    default:
                        toast = Toast.makeText(thisActivity,
                                "Some error", Toast.LENGTH_LONG);
                        toast.show();
                }
            }
        };
    }