Java接入mail工具类

        因为要发送邮件所以我特意在网络找了一下Java接入mail的工具类,没有自己喜欢的,索性自己花一上午加午休的时间封装了一个,此工具类支持(发送普通的邮件,html邮件,可以携带附件,批量发送邮件等功能)当然啦作为程序袁得有开源思想,在这里我分享给大家。

      都看到这里了,还不闭上眼睛说爱我

 首先是咱们的一个实体类,用于承载邮件内容

/**
 * @Description 邮件的通用属性实体类
 * @author shenwang
 * @version 1.0
 */
@Data
@NoArgsConstructor
public class MailEntity {
    /**
     * 邮件的文本内容
     */
    private String content;
    /**
     * 邮件标题
     */
    private String subject;
    /**
     * 邮件附件集合
     */
    private List<File> attachments;
    public MailEntity(String subject,String content){
        this.subject=subject;
        this.content=content;
    }
}

紧接着是枚举类,用于规定发送邮件的类型

/**
 * 发送邮件的类型
 * @author shenwang
 */
public enum MailType {
    HTML,COMMON
}

最后就是咱们的工具类啦!!!

/**
 * 发送163邮件
 * @author shenwang
 */
@Component
public class MailUtils {
    /**
     * 邮件发送协议
     */
    private final static String protocol = "smtp";
    /**
     * SMTP邮件服务器
     */
    private static String host = "smtp.163.com";

    /**
     * SMTP邮件服务器默认端口
     */
    private static String port = "25";
    /**
     * 是否要求身份认证
     */
    private static String isAuth = "true";
    /**
     * 是否启用调试模式(启用调试模式可打印客户端与服务器交互过程时一问一答的响应消息)
     */
    private static String isEnabledDebugMod = "true";
    /**
     * 发件人
     */
    private static String from = "ababababab@163.com";
    /**
     * 邮箱密码或授权码
     */
    private static String password="YCBKUZDEFYMPHQJD";

    /**
     * 初始化连接邮件服务器的会话信息
     */
    private static Properties properties = null;

    static {
        properties = new Properties();
        properties.setProperty("mail.transport.protocol", protocol);
        properties.setProperty("mail.smtp.host", host);
        properties.setProperty("mail.smtp.port", port);
        properties.setProperty("mail.smtp.auth", isAuth);
        properties.setProperty("mail.debug",isEnabledDebugMod);
    }

    /**
     * 日志记录
     */
    private static Logger logger = LoggerFactory.getLogger(MailUtils.class);

    /**
     * 发送html邮件
     * @param mailInfo 邮件信息
     * @return
     */
    @Async
    public boolean sendHtmlMail(String to, MailEntity mailInfo){

        Session session = Session.getInstance(properties);

        Transport transport=null;
        //新建消息
        Message message=new MimeMessage(session);
        try {
            transport = session.getTransport();
            // set from 头部字段
            message.setFrom(new InternetAddress(from));
            //set to 头部字段
            message.setRecipient(Message.RecipientType.TO,new InternetAddress(to));
            //设置subject 头字段
            message.setSubject(mailInfo.getSubject());
            //创建多重消息
            Multipart multipart = new MimeMultipart();
            //如果有附件,则添加附件
            List<File> attachments = mailInfo.getAttachments();
            if(attachments!=null&&attachments.size()>0){
                //创建消息部分
                MimeBodyPart messageBodyPart = new MimeBodyPart();
                messageBodyPart.setContent(mailInfo.getContent(),"text/html;charset=utf-8");
                //设置文本消息部分
                multipart.addBodyPart(messageBodyPart);
                for (File file : attachments){
                    //附件部分
                    MimeBodyPart messageBodyPart2 = new MimeBodyPart();
                    //获取文件路径
                    String path = file.getPath();
                    DataSource source = new FileDataSource(path);
                    messageBodyPart2.setDataHandler(new DataHandler(source));
                    messageBodyPart2.setFileName(file.getName());
                    multipart.addBodyPart(messageBodyPart2);
                }
                //发送完整消息
                message.setContent(multipart);
            }
            else {
                //设置邮件内容
                message.setContent(mailInfo.getContent(),"text/html;charset=utf-8");
            }
            //设置密码
            transport.connect(host, from, password);
            //发送消息
            transport.sendMessage(message,new Address[]{new InternetAddress(to)});
            return true;
        } catch (MessagingException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 发送带有附件的email
     * @param mailInfo 邮件信息
     * @return
     */
    @Async
    public boolean sendMail(String to,MailEntity mailInfo){
        Session session = Session.getInstance(properties);
        Transport transport=null;
        //新建消息
        Message message = new MimeMessage(session);
        try{
            transport = session.getTransport();
            // set from 头部字段
            message.setFrom(new InternetAddress(from));
            //set to 头部字段
            message.setRecipient(Message.RecipientType.TO,new InternetAddress(to));
            //设置subject 头字段
            message.setSubject(mailInfo.getSubject());
            //创建多重消息
            Multipart multipart = new MimeMultipart();
            //如果有附件,则添加附件
            List<File> attachments = mailInfo.getAttachments();
            if(attachments!=null&&attachments.size()>0){
                //创建消息部分
                MimeBodyPart messageBodyPart = new MimeBodyPart();
                messageBodyPart.setText(mailInfo.getContent());
                //设置文本消息部分
                multipart.addBodyPart(messageBodyPart);
                for (File file : attachments){
                    //附件部分
                    MimeBodyPart messageBodyPart2 = new MimeBodyPart();
                    //获取文件路径
                    String path = file.getPath();
                    DataSource source = new FileDataSource(path);
                    messageBodyPart2.setDataHandler(new DataHandler(source));
                    messageBodyPart2.setFileName(file.getName());
                    multipart.addBodyPart(messageBodyPart2);
                }
                //发送完整消息
                message.setContent(multipart);
            }
            else {
                //设置邮件内容
                message.setText(mailInfo.getContent());
            }
            //设置密码
            transport.connect(host, from, password);
            //发送消息
            transport.sendMessage(message,new Address[]{new InternetAddress(to)});
            return true;
        } catch (NoSuchProviderException e) {
            e.printStackTrace();
        } catch (AddressException e) {
            e.printStackTrace();
        } catch (MessagingException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 批量发送邮件
     * @param toList 所有收件人地址
     * @param mailInfo 邮件信息
     * @return
     */
    @Async
    public Map<String,Object> batchSend(List<String> toList, MailEntity mailInfo, String mailType){
            //成功记录数
            int successCount=0;
            for (String to:toList){
                boolean flag =false;
                //发送普通邮件
                if (mailType.equals("COMMON")){
                    flag=sendMail(to, mailInfo);
                    if(flag){
                        successCount++;
                    }
                }
                //发送html邮件
                else if (mailType.equals("HTML")){
                    flag=sendHtmlMail(to,mailInfo);
                    if(flag){
                        successCount++;
                    }
                }
            }
            //返回结果
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("successCount",successCount);
            resultMap.put("failedCount",toList.size()-successCount);
            resultMap.put("total",toList.size());
            return resultMap;
    }

}

紧接着咱们就可以去测试啦

下面是测试代码:


/**
 * 发送邮件测试类
 */
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
public class MailTest {
    @Autowired
    private MailUtils mailUtils;
    /**
     * 发送消息
     */
    @Test
    public void sendMail() {
        String to="wulawulawula@163.com";
        MailEntity mailInfo=new MailEntity("一封有味道的邮件","来自旺仔发送的一封有味道的邮件");
        System.out.println(mailUtils.sendMail(to,mailInfo)?"发送成功":"发送失败");;
    }

    /**
     * 发送html邮件
     */
    @Test
    public void sendHtmlMail(){
        //准备参数
        String to="wulawulawula@163.com";
        //发送邮件
        MailEntity mailInfo=new MailEntity("一封有味道的html邮件","<h3 style='color:blue'>您好,这是旺仔给您发送的有味道的html文件<h3>");
       System.out.println(mailUtils.sendHtmlMail(to,mailInfo)?"发送成功":"发送失败");
    }
    /**
     * 发送html邮件,并携带附件
     */
    @Test
    public void sendEnclosureHtmlMail(){
        //准备参数
        String to="wulawulawula@163.com";
        //发送邮件
        MailEntity mailInfo=new MailEntity("一封有味道的html邮件","<h3 style='color:blue'>您好,这是旺仔给您发送的有味道的html文件<h3>");
        List<File> attachments=new ArrayList<>();
        File file= new File("F:\\shenwang\\file\\test mail\\ahua.png");
        File file2= new File("F:\\shenwang\\file\\download\\userList.xls");
        attachments.add(file2);
        attachments.add(file);
        mailInfo.setAttachments(attachments);
        System.out.println(mailUtils.sendHtmlMail(to,mailInfo)?"发送成功":"发送失败");
    }

    /**
     * 发送附件
     */
    @Test
    public void sendEnclosureMail(){
        //收件人
        String to=("wulawulawula@163.com");
        //邮件信息
        MailEntity mailInfo = new MailEntity();
        mailInfo.setSubject("有味道的附件邮件");
        mailInfo.setContent("您好,这是旺仔给您发送的一个测试附件的邮件");
        List<File> attachments=new ArrayList<>();
        File file= new File("F:\\shenwang\\file\\test mail\\ahua.png");
        File file2= new File("F:\\shenwang\\file\\download\\userList.xls");
        attachments.add(file2);
        attachments.add(file);
        mailInfo.setAttachments(attachments);
        //发送消息
        System.out.println(mailUtils.sendMail(to,mailInfo)?"发送成功":"发送失败");
    }

    /**
     * 批量发送
     */
    @Test
    public void batchSend(){
        //收件人
        String to=("wulawulawula@163.com");
        //邮件信息
        MailEntity mailInfo = new MailEntity();
        mailInfo.setSubject("有味道的附件邮件");
        mailInfo.setContent("您好,这是旺仔给您发送的一个测试附件的邮件");
        List<File> attachments=new ArrayList<>();
        File file= new File("F:\\shenwang\\file\\test mail\\ahua.png");
        File file2= new File("F:\\shenwang\\file\\download\\userList.xls");
        attachments.add(file2);
        attachments.add(file);
        mailInfo.setAttachments(attachments);
        List<String> toList=new ArrayList<>();
        toList.add(to);
        toList.add(to);
        mailUtils.batchSend(toList,mailInfo, String.valueOf(MailType.COMMON));
    }

    /**
     * 批量发送html邮件
     */
    @Test
    public void batchSendHtmlMwail(){
        //收件人
        String to=("wulawulawula@163.com");
        //邮件信息
        MailEntity mailInfo = new MailEntity();
        mailInfo.setSubject("有味道的附件邮件");
        mailInfo.setContent("<h3 style='color:blue'>您好,这是旺仔给您发送的有味道的html文件<h3>");
        List<File> attachments=new ArrayList<>();
        File file= new File("F:\\shenwang\\file\\test mail\\ahua.png");
        File file2= new File("F:\\shenwang\\file\\download\\userList.xls");
        attachments.add(file2);
        attachments.add(file);
        mailInfo.setAttachments(attachments);
        List<String> toList=new ArrayList<>();
        toList.add(to);
        toList.add(to);
        mailUtils.batchSend(toList,mailInfo, String.valueOf(MailType.HTML));
    }
}

 大家用的时候记得改邮箱地址窝~为了安全起见我在上面的代码上写的邮箱地址都是错的,咱们可以改成自己的。

当然啦这还是有一些bug,没有提醒人家说不能为空这样的,如果你,收件人的邮箱地址不填肯定是会报错的,大家可以自己去优化。

over上测试结果:

因为内容的原因我就放最后一个测试的结果啦,不然后面一堆图片,大家看着也懵哈哈哈,最后一个方法是批量发送html邮件,并携带附件:

咱点开一个邮件看一下:

 

测试成功,在平时的学习中,这个工具类是够用了,其中这个工具类中因为写的仓促,也是昨天才刚接触java接入mail所以多多少少还是有些bug,如果大家有用到不如意的地方可以自行去修改。 

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值