Java-工具类之发送邮件

来源:互联网 发布:淘宝9月什么时候有活动 编辑:程序博客网 时间:2024/05/16 15:10

  • 步骤
  • 实例
  • 依赖包
    • 不带有附件的邮件
      • 工具类一
      • 工具类二
    • 带有附件的邮件


步骤

  • 使用properties创建一个Session对象

  • 使用Session创建Message对象,然后设置邮件主题和正文,如果需要发送附件,就需要用到Multipart对象

  • 使用Transport对象发送邮件


实例

代码已托管到 https://github.com/yangshangwei/commonUtils


依赖包

    <!-- https://mvnrepository.com/artifact/com.sun.mail/javax.mail -->        <dependency>            <groupId>com.sun.mail</groupId>            <artifactId>javax.mail</artifactId>            <version>${javax.mail.version}</version>        </dependency>

这里写图片描述


不带有附件的邮件

工具类一

package com.artisan.commonUtils.mail;import java.util.Properties;import javax.mail.Address;import javax.mail.Message;import javax.mail.MessagingException;import javax.mail.Session;import javax.mail.Transport;import javax.mail.internet.InternetAddress;import javax.mail.internet.MimeMessage;import com.sun.mail.util.MailSSLSocketFactory;/** *  * @ClassName: SendEmailUtil * @Description: 发送邮件工具类 * @author: Mr.Yang * @date: 2017年8月28日 下午4:50:35 */public class SendEmailUtil {    /**     *      *      * @Title: sendEmail     *      * @Description: 发送邮件工具类方法     *      * @param sendEmail     *            发件人地址     * @param sendEmailPwd     *            授权码代替密码(更安全) 授权码的获取:进入个人邮箱,点击设置–>账户, SMTP服务选项 默认情况下这个选项是不开启的。     *            点击开启腾讯会进行身份验证,身份验证通过以后,会收到一个用于使用SMTP的16位口令,     *            验证身份的过程中把收到的口令保存下来,因为后面要使用SMTP功能必须要用到这个口令。     * @param title     *            邮件标题     * @param content     *            邮件内容     * @param toEmilAddress     *            收件人地址     * @throws Exception     *      * @return: void     */    public static void sendEmail(String sendEmail, String sendEmailPwd, String title, String content,            String[] toEmilAddress) throws Exception {        Properties props = new Properties();        // 开启debug调试,以便在控制台查看        props.setProperty("mail.debug", "true");        // 设置邮件服务器主机名        props.setProperty("mail.host", "smtp.qq.com");        // 发送服务器需要身份验证        props.setProperty("mail.smtp.auth", "true");        // 发送邮件协议名称        props.setProperty("mail.transport.protocol", "smtp");        // 开启SSL加密,否则会失败        MailSSLSocketFactory sf = new MailSSLSocketFactory();        sf.setTrustAllHosts(true);        props.put("mail.smtp.ssl.enable", "true");        props.put("mail.smtp.ssl.socketFactory", sf);        Session session = Session.getInstance(props);        Message msg = new MimeMessage(session);        // 发送的邮箱地址        msg.setFrom(new InternetAddress(sendEmail));        // 设置标题        msg.setSubject(title);        // 设置内容        msg.setContent(content, "text/html;charset=gbk;");        Transport transport = session.getTransport();        // 设置服务器以及账号和密码        // 这里端口改成465        transport.connect("smtp.qq.com", sendEmail, sendEmailPwd);        // 发送到的邮箱地址        transport.sendMessage(msg, getAddress(toEmilAddress));        if(transport!=null){             try {                 transport.close();             } catch (MessagingException e) {                 e.printStackTrace();             }         }    }     /**     *      * @Title: getAddress     * @Description: 遍历收件人信息     * @param emilAddress     * @return     * @throws Exception     * @return: Address[]     */    private static Address[] getAddress(String[] emilAddress) throws Exception {        Address[] address = new Address[emilAddress.length];        for (int i = 0; i < address.length; i++) {            address[i] = new InternetAddress(emilAddress[i]);        }        return address;    }    /**     *      *      * @Title: main     *      * @Description: 测试     *      * @param args     * @throws Exception     *      * @return: void     */    public static void main(String[] args) throws Exception {        /**         * * @param sendEmail 发件人地址         *          * @param sendEmailPwd         *            授权码代替密码(更安全)          * @param title         *            邮件标题         * @param content         *            邮件内容         * @param toEmilAddress         *            收件人地址         */        SendEmailUtil.sendEmail("xxxxx@qq.com", "xxxxxxx", "testEmail", "testcontent",                new String[] { "xxxxx@gmail.com", "xxxx@qq.com" });    }}/** * 在发邮件过程中有的人会发送不成功,出现如下错误:  * javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure *  * 这个是jdk导致的,jdk里面有一个jce的包,安全性机制导致的访问https会报错,官网上有替代的jar包,换掉就好了 *  * 对应包的下载地址: * http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html *  * 下载好后,直接替换掉本地JDK中的对应的两的包就好了。 *  */

测试结果:

这里写图片描述

工具类二

#smtp servermail.smtp.host=smtp.qq.com#Authenticationmail.smtp.auth=true#--------------------------------------------------------------#Account of sender's mailbox mail.sender.username=xxxxxxx@qq.com#Authorization code of  sender's mailbox mail.sender.password=xxxxxxx
package com.artisan.commonUtils.mail;import java.io.IOException;import java.io.InputStream;import java.security.GeneralSecurityException;import java.util.Properties;import javax.mail.Address;import javax.mail.MessagingException;import javax.mail.Session;import javax.mail.Transport;import javax.mail.internet.InternetAddress;import javax.mail.internet.MimeMessage;import javax.mail.internet.MimeUtility;import com.sun.mail.util.MailSSLSocketFactory;/** *  * @ClassName: SendMailUtil2 * @Description: 发送邮件工具类 * @author: Mr.Yang * @date: 2017年8月28日 下午4:50:17 */public class SendMailUtil2 {     /**     * Message对象将存储我们实际发送的电子邮件信息,     * Message对象被作为一个MimeMessage对象来创建并且需要知道应当选择哪一个JavaMail session。     */    private MimeMessage message;    /**     * Session类代表JavaMail中的一个邮件会话。     * 每一个基于JavaMail的应用程序至少有一个Session(可以有任意多的Session)。     *      * JavaMail需要Properties来创建一个session对象。     * 寻找"mail.smtp.host"    属性值就是发送邮件的主机     * 寻找"mail.smtp.auth"    身份验证,目前免费邮件服务器都需要这一项     */    private Session session;    /***     * 邮件是既可以被发送也可以被受到。JavaMail使用了两个不同的类来完成这两个功能:Transport 和 Store。      * Transport 是用来发送信息的,而Store用来收信。这里我们只需要用到Transport对象。     */    private Transport transport;    private String mailHost="";    private String sender_username="";    private String sender_password="";    private Properties properties = new Properties();    /*     * 初始化方法     */    public SendMailUtil2(boolean debug) {        InputStream in = SendMailUtil2.class.getResourceAsStream("SMTPMailServer.properties");        try {            properties.load(in);            this.mailHost = properties.getProperty("mail.smtp.host");            this.sender_username = properties.getProperty("mail.sender.username");            this.sender_password = properties.getProperty("mail.sender.password");            // 开启SSL加密,否则会失败            MailSSLSocketFactory sf = new MailSSLSocketFactory();            sf.setTrustAllHosts(true);            properties.put("mail.smtp.ssl.enable", "true");            properties.put("mail.smtp.ssl.socketFactory", sf);        } catch (IOException e) {            e.printStackTrace();        } catch (GeneralSecurityException e) {            e.printStackTrace();        }        session = Session.getInstance(properties);        session.setDebug(debug);//开启后有调试信息        message = new MimeMessage(session);    }    /**     * 发送邮件     *      * @param subject     *            邮件主题     * @param sendHtml     *            邮件内容     * @param receiveUser     *            收件人地址     */    public void doSendHtmlEmail(String subject, String emailContent,            String[] toEmailAddress) {        try {            // 发件人            //InternetAddress from = new InternetAddress(sender_username);            // 下面这个是设置发送人的Nick name            InternetAddress from = new InternetAddress(MimeUtility.encodeWord("小工匠")+" <"+sender_username+">");            message.setFrom(from);            // 邮件主题            message.setSubject(subject);            // 邮件内容,也可以使纯文本"text/plain"            message.setContent(emailContent, "text/html;charset=UTF-8");            // 保存邮件            message.saveChanges();            transport = session.getTransport("smtp");            // smtp验证  用户名和授权码            transport.connect(mailHost, sender_username, sender_password);            // 发送            transport.sendMessage(message,  getAddress(toEmailAddress));            System.out.println("send email successfully ");        } catch (Exception e) {            e.printStackTrace();        }finally {            if(transport!=null){                try {                    transport.close();                } catch (MessagingException e) {                    e.printStackTrace();                }            }        }    }    /**     *      * @Title: getAddress     * @Description: 遍历收件人信息     * @param emilAddress     * @return     * @throws Exception     * @return: Address[]     */    private static Address[] getAddress(String[] emilAddress) throws Exception {        Address[] address = new Address[emilAddress.length];        for (int i = 0; i < address.length; i++) {            address[i] = new InternetAddress(emilAddress[i]);        }        return address;    }    public static void main(String[] args) {        SendMailUtil2 se = new SendMailUtil2(true);// 开启调试        se.doSendHtmlEmail("1邮件主题", "邮件内容", new String[]{"xxxxx@gmail.com","xxxxxxxx@qq.com"});    }}

测试结果:

这里写图片描述


带有附件的邮件

#smtp servermail.smtp.host=smtp.qq.com#Authenticationmail.smtp.auth=true#--------------------------------------------------------------#Account of sender's mailbox mail.sender.username=xxxxxxx@qq.com#Authorization code of  sender's mailbox mail.sender.password=xxxxxxx
package com.artisan.commonUtils.mail;import java.io.File;import java.io.IOException;import java.io.InputStream;import java.security.GeneralSecurityException;import java.util.Properties;import javax.activation.DataHandler;import javax.activation.DataSource;import javax.activation.FileDataSource;import javax.mail.Address;import javax.mail.BodyPart;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;import javax.mail.internet.MimeUtility;import com.sun.mail.util.MailSSLSocketFactory;/** *  * @ClassName: SendEmailWithAttachment * @Description: Email发送附件 [如果需要发送附件,就需要用到Multipart对象] * @author: Mr.Yang * @date: 2017年8月28日 下午4:49:35 */public class SendEmailWithAttachment {    private MimeMessage message;    private Session session;    private Transport transport;    private String mailHost = "";    private String sender_username = "";    private String sender_password = "";    private Properties properties = new Properties();    /*     * 初始化方法     */    public SendEmailWithAttachment(boolean debug) {        InputStream in = SendEmailWithAttachment.class.getResourceAsStream("SMTPMailServer.properties");        try {            properties.load(in);            this.mailHost = properties.getProperty("mail.smtp.host");            this.sender_username = properties.getProperty("mail.sender.username");            this.sender_password = properties.getProperty("mail.sender.password");            // 开启SSL加密,否则会失败            MailSSLSocketFactory sf = new MailSSLSocketFactory();            sf.setTrustAllHosts(true);            properties.put("mail.smtp.ssl.enable", "true");            properties.put("mail.smtp.ssl.socketFactory", sf);        } catch (IOException e) {            e.printStackTrace();        } catch (GeneralSecurityException e) {            e.printStackTrace();        }        session = Session.getInstance(properties);        session.setDebug(debug);// 开启后有调试信息        message = new MimeMessage(session);    }    /**     * 发送邮件     *      * @param subject     *            邮件主题     * @param sendHtml     *            邮件内容     * @param receiveUser     *            收件人地址     * @param attachment     *            附件     */    public void doSendHtmlEmail(String subject, String sendHtml, String[] receiveUsers, File attachment) {        try {            // 发件人            InternetAddress from = new InternetAddress(sender_username);            message.setFrom(from);            // 邮件主题            message.setSubject(subject);            // 向multipart对象中添加邮件的各个部分内容,包括文本内容和附件            Multipart multipart = new MimeMultipart();            // 添加邮件正文            BodyPart contentPart = new MimeBodyPart();            contentPart.setContent(sendHtml, "text/html;charset=UTF-8");            multipart.addBodyPart(contentPart);            // 添加附件的内容            if (attachment != null) {                BodyPart attachmentBodyPart = new MimeBodyPart();                DataSource source = new FileDataSource(attachment);                attachmentBodyPart.setDataHandler(new DataHandler(source));                // 网上流传的解决文件名乱码的方法,其实用MimeUtility.encodeWord就可以很方便的搞定                // 这里很重要,通过下面的Base64编码的转换可以保证你的中文附件标题名在发送时不会变成乱码                //sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();                //messageBodyPart.setFileName("=?GBK?B?" + enc.encode(attachment.getName().getBytes()) + "?=");                //MimeUtility.encodeWord可以避免文件名乱码                attachmentBodyPart.setFileName(MimeUtility.encodeWord(attachment.getName()));                multipart.addBodyPart(attachmentBodyPart);            }            // 将multipart对象放到message中            message.setContent(multipart);            // 保存邮件            message.saveChanges();            transport = session.getTransport("smtp");            // smtp验证            transport.connect(mailHost, sender_username, sender_password);            // 发送            transport.sendMessage(message, getAddress(receiveUsers));            System.out.println("send success!");        } catch (Exception e) {            e.printStackTrace();        } finally {            if (transport != null) {                try {                    transport.close();                } catch (MessagingException e) {                    e.printStackTrace();                }            }        }    }    /**     * @Title: getAddress     * @Description: 遍历收件人信息     * @param emilAddress     * @return     * @throws Exception     * @return: Address[]     */    private static Address[] getAddress(String[] emilAddress) throws Exception {        Address[] address = new Address[emilAddress.length];        for (int i = 0; i < address.length; i++) {            address[i] = new InternetAddress(emilAddress[i]);        }        return address;    }    public static void main(String[] args) {        SendEmailWithAttachment se = new SendEmailWithAttachment(true);        File attached = new File("D:\\workspace\\ws-java-base\\commonUtils\\pom.xml");        se.doSendHtmlEmail("邮件主题带有附件", "邮件内容", new String[]{"yswcomeon@gmail.com"}, attached);    }}

测试结果:

这里写图片描述

原创粉丝点击