发送邮件工具类,非常实用

Posted 格子衫111

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了发送邮件工具类,非常实用相关的知识,希望对你有一定的参考价值。

说明:本示例是基于springboot工程编写的

一、导入pom依赖

pom.xml

        <!--发邮件需要-->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-email</artifactId>
            <version>1.3.3</version>
        </dependency>

        <!--easyexcel,根据数据生成邮件附件 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>easyexcel</artifactId>
            <version>3.1.3</version>
            <exclusions>
                <exclusion>
                    <groupId>org.apache.poi</groupId>
                    <artifactId>poi</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.apache.poi</groupId>
                    <artifactId>poi-ooxml</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <!--     实体类的@Data注解需要-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.12</version>
            <scope>provided</scope>
        </dependency>
        <!--        加载配置文件工具类需要-->
        <dependency>
            <groupId>commons-configuration</groupId>
            <artifactId>commons-configuration</artifactId>
            <version>1.9</version>
        </dependency>

二、编写邮件相关工具类

EmailUtils.java

package com.zwt.utils;

import com.zwt.utils.properties.PropUtils;
import java.io.File;
import java.util.Arrays;
import javax.mail.internet.MimeUtility;
import org.apache.commons.mail.Email;
import org.apache.commons.mail.EmailAttachment;
import org.apache.commons.mail.htmlEmail;
import org.apache.commons.mail.SimpleEmail;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class EmailUtils 
    private static final Logger LOGGER = LoggerFactory.getLogger(EmailUtils.class);

    //发件人邮箱
    private static String MAIL_FROM_EAMIL;
    //邮箱服务器HOST
    private static String MAIL_SMTP_HOST;
    //邮箱服务器端口号
    private static int MAIL_SMTP_PORT;
    //是否需要认证
    private static Boolean MAIL_SMTP_AUTH;
    //邮箱认证登录名
    private static String MAIL_SMTP_AUTH_USERNAME;
    //邮箱认证登录密码
    private static String MAIL_SMTP_AUTH_PASSWORD;
    //邮箱字符编码
    private static String MAIL_ENCODING;
    //是否需要SSL连接
    private static Boolean MAIL_SMTP_SSL;
    //收件人邮箱数组,new String[]  "xxx@qq.com" 
    private static String[] MAIL_RECEIVERS;
    //发件人名称
    private static String MAIL_FROM_NAME = "我是发件人";
    //邮件主题
    private static String MAIL_SUBJECT = "我是发件人主题";
    //邮件内容模板
    private static String MAIL_BODY_TEMPLATE;
    //发送邮件附件 临时存储目录
    public static String MAIL_ATTACH_TEMP_DIR="mailAttach";
    //邮件附件命名
    public static String MAIL_ATTACH_NAME = "邮件附件示例";

    //静态代码块,加载配置文件内容
    static 
        try 
            PropUtils config = PropUtils.getInstance();
            MAIL_RECEIVERS = config.getStringArray("mail.receivers");  //使用配置文件中的内容
            MAIL_FROM_EAMIL = config.getString("mail.from.email", "xxx@qq.com"); //这里需要根据自身情况更改
            MAIL_SMTP_HOST = config.getString("mail.smtp.host", "exchange.cn.xxx.com"); //这里需要根据自身情况更改
            MAIL_SMTP_PORT = config.getInt("mail.smtp.port", 25);
            MAIL_SMTP_AUTH = config.getBoolean("mail.smtp.auth", false);
            MAIL_SMTP_AUTH_USERNAME = config.getString("mail.smtp.username", "xxx");  //这里需要根据自身情况更改
            MAIL_SMTP_AUTH_PASSWORD = EncryptUtils.decrypt(config.getString("mail.smtp.password", "xxx")); //这里需要根据自身情况更改
            MAIL_ENCODING = config.getString("mail.encoding", "GBK");
            MAIL_SMTP_SSL = config.getBoolean("mail.smtp.ssl", false);
            MAIL_ATTACH_TEMP_DIR = config.getString("mail.attach.temp.dir", "mailAttach");
            MAIL_FROM_NAME = config.getString("supply.mail.from.name", "我是发件人"); //这里需要根据自身情况更改
            MAIL_SUBJECT = config.getString("supply.mail.summary.subject", "我是发件人主题"); //这里需要根据自身情况更改
            MAIL_BODY_TEMPLATE = config.getString("mail.body.template", "this is my test massage:\\r\\n\\r\\n%s\\r\\n\\r\\n-----------------------------\\r\\nThis email is sent by system automatically, do NOT reply this email directly!");
         catch (Exception e) 
            LOGGER.error("Can't read application.properties", e);
        
    


    /**
     * 发送不带附件邮件,邮件正文不带表格
     * @param message 邮件正文消息
     */
    public static void sendCommonEmail(final String message) 
        try 
            Email email = new SimpleEmail();
            email.setHostName(MAIL_SMTP_HOST);
            email.setSmtpPort(MAIL_SMTP_PORT);
            if (MAIL_SMTP_AUTH) 
                email.setAuthentication(MAIL_SMTP_AUTH_USERNAME, MAIL_SMTP_AUTH_PASSWORD);
            
            email.setCharset(MAIL_ENCODING);
            email.setSSLOnConnect(MAIL_SMTP_SSL);
            email.setFrom(MAIL_FROM_EAMIL, MAIL_FROM_NAME);
            email.addTo(MAIL_RECEIVERS);
            email.setSubject(MAIL_SUBJECT);
            email.setMsg(String.format(MAIL_BODY_TEMPLATE, message));
            email.send();
         catch (Exception e) 
            LOGGER.error(String.format(
                            "Can't send summary email: Host:%s, Port:%d, User:%s, From:%s, To:%s, Subject:%s, Message:%s",
                            MAIL_SMTP_HOST, MAIL_SMTP_PORT, MAIL_SMTP_AUTH_USERNAME, MAIL_FROM_EAMIL,
                            Arrays.toString(MAIL_RECEIVERS), MAIL_SUBJECT, message), e);
        
    

    /**
     * 发送不带附件邮件,邮件正文带表格内容
     * @param message 邮件正文消息
     */
    public static void sendHTMLEmail(final String message) 
        try 
            HtmlEmail email = new HtmlEmail();
            email.setHostName(MAIL_SMTP_HOST);
            email.setSmtpPort(MAIL_SMTP_PORT);
            email.setCharset(MAIL_ENCODING);
            if (MAIL_SMTP_AUTH) 
                email.setAuthentication(MAIL_SMTP_AUTH_USERNAME, MAIL_SMTP_AUTH_PASSWORD);
            
            email.setSSLOnConnect(MAIL_SMTP_SSL);
            email.setFrom(MAIL_FROM_EAMIL, MAIL_FROM_NAME);
            email.addTo(MAIL_RECEIVERS);
            email.setSubject(MAIL_SUBJECT);
            email.setHtmlMsg(message);
            email.setTextMsg("Your email client does not support HTML message.");
            email.send();
         catch (Exception e) 
            LOGGER.error(String.format(
                            "Can't send summary email: Host:%s, Port:%d, User:%s, From:%s, To:%s, Subject:%s, Message:%s",
                            MAIL_SMTP_HOST, MAIL_SMTP_PORT, MAIL_SMTP_AUTH_USERNAME, MAIL_FROM_EAMIL,
                            Arrays.toString(MAIL_RECEIVERS), MAIL_SUBJECT, message), e);
        
    

    /**
     * 发送附件邮件
     * @param message 邮件正文消息
     * @param fileName 附件全路径 dir+attachName
     * @param attachName 附件名 示例:邮件附件示例2022-12-16.xlsl
     */
    public static void sendEmailWithAttach(final String message,String fileName,String attachName) 
        try 
            HtmlEmail email = new HtmlEmail();
            email.setHostName(MAIL_SMTP_HOST);      //指定邮件服务器
            email.setSmtpPort(MAIL_SMTP_PORT);         //端口
            email.setCharset(MAIL_ENCODING);           //字符集
            if (MAIL_SMTP_AUTH) 
                email.setAuthentication(MAIL_SMTP_AUTH_USERNAME, MAIL_SMTP_AUTH_PASSWORD);  //身份验证
            
            email.setSSLOnConnect(MAIL_SMTP_SSL);
            email.setFrom(MAIL_FROM_EAMIL, MAIL_FROM_NAME);       //邮件发送人
            EmailAttachment emailAttachment = new EmailAttachment();        //附件对象
            emailAttachment.setPath(fileName);          //附件路径
            emailAttachment.setName(MimeUtility.encodeText(fileName));
            emailAttachment.setDisposition(EmailAttachment.ATTACHMENT);
            emailAttachment.setDescription(attachName);     //附件名称
            email.attach(emailAttachment);          //发送附件
            email.addTo(MAIL_RECEIVERS);      //收件人
            email.setSubject(MAIL_SUBJECT);       //主题
            email.setHtmlMsg(message);          //邮件正文
            email.setTextMsg("Your email client does not support HTML message.");
            email.send();

            // 删除临时目录中的附件
            File file = new File(fileName);
            if (file.delete())
                LOGGER.info("---附件删除成功---fileName:"+fileName);
            else 
                LOGGER.info("---附件删除失败---fileName:"+fileName);
            
         catch (Exception e) 
            LOGGER.error(String.format(
                    "Can't send summary email: Host:%s, Port:%d, User:%s, From:%s, To:%s, Subject:%s, Message:%s",
                    MAIL_SMTP_HOST, MAIL_SMTP_PORT, MAIL_SMTP_AUTH_USERNAME, MAIL_FROM_EAMIL,
                    Arrays.toString(MAIL_RECEIVERS), MAIL_SUBJECT, message), e);
        
    



EncryptUtils.java

package com.zwt.utils;

import com.zwt.utils.properties.PropUtils;
import java.util.Scanner;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * AES加解密工具类
 */
public class EncryptUtils 

    private static final Logger log = LoggerFactory.getLogger(EncryptUtils.class);

    private static String TOKEN;

    static 
        PropUtils config = PropUtils.getInstance();
        TOKEN = config.getString("encry.token");
        if (TOKEN == null || TOKEN.trim().length() != 16) 
            TOKEN = null;
            throw new RuntimeException(
                    "Invalid token string! Token can't be blank and length must be 16!");
        
    

    private static final SecretKeySpec key = new SecretKeySpec(TOKEN.trim().getBytes(), "AES");

    private static String encodeBase64(byte[] msg) 
        Base64 encoder = new Base64();
        return encoder.encodeToString(msg);
    

    private static byte[] decodeBase64(String msg) 
        Base64 decoder = new Base64();
        return decoder.decode(msg);
    

    /**
     * 加密
     * @param p 明文
     * @return
     * @throws Exception
     */
    public static String encrypt(String p) throws Exception 
        if (TOKEN == null) 
            throw new RuntimeException("Can't encrypt password because token is invalid!");
        
        Cipher cipher = Cipher.getInstance("AES");
        byte[] byteContent = p.getBytes("UTF-8");
        cipher.init(Cipher.ENCRYPT_MODE, key);
        byte[] result = cipher.doFinal(byteContent);
        return encodeBase64(result);
    

    /**
     * 解密
     * @param p 密文
     * @return
     * @throws Exception
     */
    public static String decrypt(String p) throws Exception 
        if (TOKEN == null) 
            throw new RuntimeException("Can't decrypt password because token is invalid!");
        
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, key);
        return new String(cipher.doFinal(decodeBase64(p)), "UTF-8");
    

    /**
     * 加密
     * @param p 原文
     * @param token
     * @return
     * @throws Exception
     */
    public static String encrypt(String p, String token) throws Exception 
        SecretKeySpec key = new SecretKeySpec(tok

以上是关于发送邮件工具类,非常实用的主要内容,如果未能解决你的问题,请参考以下文章

发送邮件工具类,非常实用

Python实用工具巧妙利用Python实现发送带附件的邮件

[Java] JavaMail 发送 html 格式带附件的邮件

邮件实现详解------JavaMail 发送(带图片和附件)和接收邮件

c#发送邮件,可发送多个附件

使用 mandrill 发送邮件时附件的文件大小限制