Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> android後台發送郵件

android後台發送郵件

編輯:關於Android編程


public class SendEmail {
    private static final String TAG = "SendEmail";
    //要發送Email地址
    private String mailTo = null;
    //郵件發送來源地址
    private String mailFrom = null;
    //SMTP主機地址
    private String smtpHost = null;
    //是否啟用調試
    private boolean debug = false;

    private String messageBasePath = null;
    //Email主題
    private String subject;

    public void setMailTo(String mailTo) {
        this.mailTo = mailTo;
    }

    public void setMailFrom(String mailFrom) {
        this.mailFrom = mailFrom;
    }

    public void setSmtpHost(String smtpHost) {
        this.smtpHost = smtpHost;
    }

    public void setDebug(boolean debug) {
        this.debug = debug;
    }

    public void setMessageBasePath(String messageBasePath) {
        this.messageBasePath = messageBasePath;
    }

    public void setSubject(String subject) {
        this.subject = subject;
    }

    public void setMsgContent(String msgContent) {
        this.msgContent = msgContent;
    }

    public void setAttachedFileList(Vector attachedFileList) {
        this.attachedFileList = attachedFileList;
    }

    public void setEmailAccount(String emailAccount) {
        this.emailAccount = emailAccount;
    }

    public void setEmailPwd(String emailPwd) {
        this.emailPwd = emailPwd;
    }

    public void setMessageContentType(String messageContentType) {
        this.messageContentType = messageContentType;
    }

    public void setEmailbccTo(String emailbccTo) {
        this.emailbccTo = emailbccTo;
    }

    public void setEmailccTo(String emailccTo) {
        this.emailccTo = emailccTo;
    }

    //Email內容
    private String msgContent;

    private Vector attachedFileList;
    private String emailAccount = null;
    private String emailPwd = null;
    private String messageContentType = "text/html;charset=utf-8";

    private String emailbccTo = null;
    private String emailccTo = null;

    /*
    默認構造函數
     */
    public SendEmail() {
        super();
    }

    private void writeEmail(Session session, Message message) throws MessagingException {
        String fileName;
        Multipart multipart = new MimeMultipart();
        //設定發件人地址
        if (mailFrom != null) {
            message.setFrom(new InternetAddress(mailFrom));
            Log.i(TAG, "發件人郵件地址:" + mailFrom);
        } else {
            Log.i(TAG, "沒有指定發件人郵件地址");
            return;
        }
        //設定收件人地址
        if (mailTo != null) {
            message.setRecipient(Message.RecipientType.TO, new InternetAddress(mailTo));
            Log.i(TAG, "收件人郵件地址:" + mailTo);
        } else {
            Log.i(TAG, "沒有指定收件人郵件地址");
            return;
        }
        //設定抄送地址
        if (emailccTo != null) {
            message.setRecipient(Message.RecipientType.CC, new InternetAddress(emailccTo));
            Log.i(TAG, "抄送郵件地址:" + emailccTo);
        } else {
            Log.i(TAG, "沒有指定抄送郵件地址");
            return;
        }
        //設定密送地址
        if (emailbccTo != null) {
            message.setRecipient(Message.RecipientType.BCC, new InternetAddress(emailbccTo));
            Log.i(TAG, "密送郵件地址:" + emailbccTo);
        } else {
            Log.i(TAG, "沒有指定密送郵件地址");
            return;
        }
        //設置郵件主題
        message.setSubject(subject);
        Log.i(TAG, "郵件主題:" + subject);
        //設置回復地址
        message.setReplyTo(new InternetAddress[]{new InternetAddress(mailFrom)});
        //創建並設置第一部分
        MimeBodyPart bodyPart = new MimeBodyPart();
        if (msgContent != null) {
            Log.i(TAG, "郵件內容:" + msgContent);
            bodyPart.setContent(msgContent, messageContentType);
        } else {
            bodyPart.setContent("", messageContentType);
        }
        multipart.addBodyPart(bodyPart);
        //附件文件到郵件中
        if (attachedFileList != null) {
            for (Enumeration fileList = attachedFileList.elements(); fileList.hasMoreElements(); ) {
                fileName = (String) fileList.nextElement();
                MimeBodyPart mBodyPart = new MimeBodyPart();

                FileDataSource fds = new FileDataSource(messageBasePath + fileName);
                Log.i(TAG, "Email發送的附件為:" + messageBasePath + fileName);
                mBodyPart.setDataHandler(new DataHandler(fds));
                mBodyPart.setFileName(fileName);
                multipart.addBodyPart(mBodyPart);
            }
        }
        Log.i(TAG, "設置郵件部分");
        message.setContent(multipart);
        message.setSentDate(new Date());
    }

    /**
     * 發送郵件方法
     *
     * @return true 表示發送成功,false表示不成功
     */
    public boolean sendEmail() {
        int loopCount;
        Properties properties = System.getProperties();
        properties.setProperty("mail.smtp.host", smtpHost);
        properties.setProperty("mail.smtp.auth", "true");
        properties.put("mail.smtp.port", "25");
        MailAuthenticator authenticator = new MailAuthenticator();
        Session session = Session.getInstance(properties, authenticator);
        session.setDebug(debug);
        MimeMessage mimeMessage = new MimeMessage(session);
//這裡如果用Transport的話會出現錯誤
        SMTPTransport transport = new SMTPTransport(session, new URLName("smtp", "smtp.qq.com", 25, null, MailAuthenticator.TENCENT_EMAIL_USER, MailAuthenticator.TENCENT_EMAIL_PWD));
        try {
            writeEmail(session, mimeMessage);
            //transport = session.getTransport("smtp");
            try {
                Log.i(TAG, "開始連接服務器");
                transport.connect(smtpHost, 25, MailAuthenticator.TENCENT_EMAIL_USER, MailAuthenticator.TENCENT_EMAIL_PWD);
            } catch (AuthenticationFailedException e) {
                e.printStackTrace();
                Log.i(TAG, "連接服務器失敗");
                return false;
            } catch (MessagingException e) {
                e.printStackTrace();
                Log.i(TAG, "發送郵件過程中出現錯誤");
                return false;
            }
            Log.i(TAG, "開始發送郵件");
            transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
            transport.close();
            Log.i(TAG, "關閉連接");
        } catch (MessagingException e) {
            e.printStackTrace();
            Log.i(TAG, "發送郵件失敗");
            return false;
        } finally {
            try {
                if (transport != null && transport.isConnected()) {
                    transport.close();
                    Log.i(TAG, "在finally中關閉連接");
                }
            } catch (MessagingException e) {
                e.printStackTrace();
            }
        }
        Log.i(TAG, "郵件發送成功");
        return true;
    }
}
tips---其中的MyAuthenticator類繼承自Authenticator,重寫這個方法即可

@Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(郵箱用戶名,密碼); }

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved