java下發電子郵件demo

來源:互聯網
上載者:User

標籤:這一   失敗   ttext   val   class   163郵箱   mem   import   source   

在實際項目中會遇到需要使用郵件註冊,或者是使用郵件找回密碼等操作,需要使用到郵件發送功能。

其實郵件的發送主要是依賴於郵件協議,只要能實現郵件協議,那麼發送郵件其實還是很容易的。這一步java類庫已經幫我們封裝好了,所以對於我們來說,我們要做的只要把參數填上,剩下的就很簡單了。下面附上發送郵件幾個工具類,然後使用163郵箱進行發送的測試類別。

- Hide code
package com.ssm.util;import java.util.Properties;/** * 發送郵件需要使用的基本資料 * @author XX * */public class MailSenderInfo {    private String mailServerHost;//發送郵件的伺服器的IP    private String mailServerPort = "25";//發送郵件的伺服器的連接埠    private String fromAddress;// 郵件寄件者的地址    private String toAddress;// 郵件接收者的地址    private String username;// 登陸郵件發送伺服器的使用者名稱    private String password;// 登陸郵件發送伺服器的密碼    private boolean validate = false;// 是否需要身分識別驗證    private String subject;// 郵件主題    private String content;// 郵件的常值內容    private String[] attachFileNames;// 郵件附件的檔案名稱    /**     * 獲得郵件會話屬性     */    public Properties getProperties() {        Properties p = new Properties();        p.put("mail.smtp.host", this.mailServerHost);        p.put("mail.smtp.port", this.mailServerPort);        p.put("mail.smtp.auth", validate ? "true" : "false");        return p;    }    /**     * 發送郵件的伺服器的IP     */    public String getMailServerHost() {        return mailServerHost;    }    /**     * 發送郵件的伺服器的IP     */    public void setMailServerHost(String mailServerHost) {        this.mailServerHost = mailServerHost;    }    /**     * 發送郵件的伺服器的連接埠     */    public String getMailServerPort() {        return mailServerPort;    }    /**     * 發送郵件的伺服器的連接埠     */    public void setMailServerPort(String mailServerPort) {        this.mailServerPort = mailServerPort;    }    /**     * 是否需要身分識別驗證     */    public boolean isValidate() {        return validate;    }    /**     * 是否需要身分識別驗證     */    public void setValidate(boolean validate) {        this.validate = validate;    }    /**     * 郵件附件的檔案名稱     */    public String[] getAttachFileNames() {        return attachFileNames;    }    /**     * 郵件附件的檔案名稱     */    public void setAttachFileNames(String[] fileNames) {        this.attachFileNames = fileNames;    }    /**     * 郵件寄件者的地址     */    public String getFromAddress() {        return fromAddress;    }    /**     * 郵件寄件者的地址     */    public void setFromAddress(String fromAddress) {        this.fromAddress = fromAddress;    }    /**     * 登陸郵件發送伺服器的密碼     */    public String getPassword() {        return password;    }    /**     * 登陸郵件發送伺服器的密碼     */    public void setPassword(String password) {        this.password = password;    }    /**     * 郵件接收者的地址     */    public String getToAddress() {        return toAddress;    }    /**     * 郵件接收者的地址     */    public void setToAddress(String toAddress) {        this.toAddress = toAddress;    }    /**     * 登陸郵件發送伺服器的使用者名稱     */    public String getUsername() {        return username;    }    /**     * 登陸郵件發送伺服器的使用者名稱     */    public void setUsername(String username) {        this.username = username;    }    /**     * 郵件主題     */    public String getSubject() {        return subject;    }    /**     * 郵件主題     */    public void setSubject(String subject) {        this.subject = subject;    }    /**     * 郵件的常值內容     */    public String getContent() {        return content;    }    /**     * 郵件的常值內容     */    public void setContent(String textContent) {        this.content = textContent;    }}
 - Hide code
package com.ssm.util;import javax.mail.*;/** * 信箱使用者資訊加密認證類 * @author XX * */public class MyAuthenticator extends Authenticator {        String username = null;//使用者名稱    String password = null;//密碼    public MyAuthenticator() {    }    public MyAuthenticator(String username, String password) {        this.username = username;        this.password = password;    }    protected PasswordAuthentication getPasswordAuthentication() {        return new PasswordAuthentication(username, password);    }}
 - Hide code
package com.ssm.util;import java.util.Date;import java.util.Properties;import javax.mail.Address;import javax.mail.BodyPart;import javax.mail.Message;import javax.mail.MessagingException;import javax.mail.Multipart;import javax.mail.Session;import javax.mail.Transport;import javax.mail.internet.InternetAddress;import javax.mail.internet.MimeBodyPart;import javax.mail.internet.MimeMessage;import javax.mail.internet.MimeMultipart;/** * 簡單郵件發送,兩種方式 * @author XX * */public class SimpleMailSender {    /**     * 以文字格式設定發送郵件     * @param mailInfo 待發送的郵件的資訊     * @return 發送成功返回true;失敗返回false     */    public boolean sendTextMail(MailSenderInfo mailInfo)     {        // 判斷是否需要身份認證        MyAuthenticator authenticator = null;        Properties pro = mailInfo.getProperties();        if (mailInfo.isValidate())         {            // 如果需要身份認證,則建立一個密碼驗證器            authenticator = new MyAuthenticator(mailInfo.getUsername(),mailInfo.getPassword());        }                // 根據郵件會話屬性和密碼驗證器構造一個發送郵件的session        Session sendMailSession = Session.getDefaultInstance(pro, authenticator);        try {            // 根據session建立一個郵件訊息            Message mailMessage = new MimeMessage(sendMailSession);            // 建立郵件寄件者地址            Address from = new InternetAddress(mailInfo.getFromAddress());            // 設定郵件訊息的寄件者            mailMessage.setFrom(from);            // 建立郵件的接收者地址,並設定到郵件訊息中            Address to = new InternetAddress(mailInfo.getToAddress());            mailMessage.setRecipient(Message.RecipientType.TO, to);            // 設定郵件訊息的主題            mailMessage.setSubject(mailInfo.getSubject());            // 設定郵件訊息發送的時間            mailMessage.setSentDate(new Date());            // 設定郵件訊息的主要內容            String mailContent = mailInfo.getContent();            mailMessage.setText(mailContent);            // 發送郵件            Transport.send(mailMessage);            return true;        } catch (MessagingException ex) {            ex.printStackTrace();        }        return false;    }    /**     * 以HTML格式發送郵件     * @param mailInfo 待發送的郵件的資訊     * @return 發送成功返回true;失敗返回false     */    public boolean sendHtmlMail(MailSenderInfo mailInfo)     {        // 判斷是否需要身份認證        MyAuthenticator authenticator = null;        Properties pro = mailInfo.getProperties();        // 如果需要身份認證,則建立一個密碼驗證器        if (mailInfo.isValidate())         {            authenticator = new MyAuthenticator(mailInfo.getUsername(),mailInfo.getPassword());        }                // 根據郵件會話屬性和密碼驗證器構造一個發送郵件的session        Session sendMailSession = Session.getDefaultInstance(pro, authenticator);                try {            // 根據session建立一個郵件訊息            Message mailMessage = new MimeMessage(sendMailSession);            // 建立郵件寄件者地址            Address from = new InternetAddress(mailInfo.getFromAddress());            // 設定郵件訊息的寄件者            mailMessage.setFrom(from);            // 建立郵件的接收者地址,並設定到郵件訊息中            Address to = new InternetAddress(mailInfo.getToAddress());            // Message.RecipientType.TO屬性工作表示接收者的類型為TO            mailMessage.setRecipient(Message.RecipientType.TO, to);            // 設定郵件訊息的主題            mailMessage.setSubject(mailInfo.getSubject());            // 設定郵件訊息發送的時間            mailMessage.setSentDate(new Date());                        // MiniMultipart類是一個容器類,包含MimeBodyPart類型的對象            Multipart mainPart = new MimeMultipart();            // 建立一個包含HTML內容的MimeBodyPart            BodyPart html = new MimeBodyPart();            // 設定HTML內容            html.setContent(mailInfo.getContent(), "text/html; charset=utf-8");            mainPart.addBodyPart(html);                        /*//設定信件的附件(用本地上的檔案作為附件)******************暫時進行使用所以注釋            html = new MimeBodyPart();            FileDataSource fds = new FileDataSource("E:\\123.doc");            DataHandler dh = new DataHandler(fds);            html.setFileName("javamail.doc");            html.setDataHandler(dh);            mainPart.addBodyPart(html);*/                        // 將MiniMultipart對象設定為郵件內容            mailMessage.setContent(mainPart);            mailMessage.saveChanges();                        // 發送郵件            Transport.send(mailMessage);            return true;        } catch (MessagingException ex) {            ex.printStackTrace();        }        return false;    }}
 - Hide code
package com.ssm.util;/** * 發送郵件測試類別 * @author XX * */public class SendMail {        public static void main(String[] args) {        SendMail.send_163();    }        // 163郵箱    public static void send_163()     {        //MailSenderInfo用於輸入發送人的資訊,方便以後如果用多個,或者不同的郵箱進行發送        MailSenderInfo mailInfo = new MailSenderInfo();        mailInfo.setMailServerHost("smtp.163.com");                //163的規定地址        mailInfo.setMailServerPort("25");                        //郵件協議規定連接埠號碼        mailInfo.setValidate(true);                                //需要身份認證                /*下面的資訊需要根據實際進行修改*/        mailInfo.setUsername("[email protected]");             // 實際寄件者        mailInfo.setPassword("11111111");                        // 您的郵箱密碼        mailInfo.setFromAddress("[email protected]");         // 設定發送人郵箱地址        mailInfo.setToAddress("[email protected]");             // 設定接受者郵箱地址        mailInfo.setSubject("標題");                                mailInfo.setContent("內容<h1>http://www.baidu.com</h1>");                        SimpleMailSender sms = new SimpleMailSender();        sms.sendTextMail(mailInfo); // 發送文體格式        sms.sendHtmlMail(mailInfo); // 發送html格式    }}
 

使用javamail-1.4.4這個版本的jar包即可。

java下發電子郵件demo

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.