APP內發送郵件

實現APP內發送郵件功能

1、在項目中導入相關架包

郵件相關架包獲取地址

2、申請郵箱,進行配置

以163郵箱爲例,申請賬號後,設置POP3/SMTP/IMAP,並開啓客戶端授權密碼,之後的在APP內的登錄將使用郵箱地址+授權碼的方式進行登錄。

3、發送郵件的代碼實現

/**
 * @author Jeff
 * @describe
 * @date 2018/5/9.
 */
public class EmailUtils {

    public static void sendEmail(String title, String content) {
        new EmailTask().execute(title,content);
    }

    /**
     * 執行發送郵件的
     */
    static class EmailTask extends AsyncTask<String,Integer,Boolean> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            //開始發送郵件
        }

        @Override
        protected Boolean doInBackground(String... params) {
            try {
                Properties props = System.getProperties();
                props.put("mail.smtp.host", "smtp.163.com");
                props.put("mail.smtp.auth", "true");
                Session session = Session.getInstance(props, null);
                Transport transport = session.getTransport("smtp");

                transport.connect("smtp.163.com", 25, BuildConfig.BUG_REPORT_EMAIL,
                        BuildConfig.EMAIL_KEY);//授權碼
                Message mailMessage = new SMTPMessage(session);
                Address from = new InternetAddress(BuildConfig.BUG_REPORT_EMAIL);
                mailMessage.setFrom(from);
                Address to = new InternetAddress(BuildConfig.BUG_REPORT_EMAIL);
                mailMessage.setRecipient(Message.RecipientType.TO, to);
                mailMessage.setSubject(params[0]);
                mailMessage.setSentDate(new Date());
                mailMessage.setText(params[1]);
                transport.sendMessage(mailMessage, mailMessage.getAllRecipients());
                return true;
            } catch (MessagingException ex) {
                ex.printStackTrace();
            }
            return false;
        }

        @Override
        protected void onProgressUpdate(Integer... progresses) {
            super.onProgressUpdate();
            //更新進度信息
        }

        @Override
        protected void onPostExecute(Boolean aBoolean) {
            super.onPostExecute(aBoolean);
            //執行完後臺任務後更新UI,顯示結果
        }

        @Override
        protected void onCancelled() {
            super.onCancelled();
            //在取消執行中的任務時更改UI
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章