SpringBoot整合邮件发送工具类

/**
 * @author hzb
 * @Title:
 * @Package
 * @Description:
 * @date 2021/7/2019:08
 */
public class SendMailUtil {

    private static Logger Log = (Logger) LoggerFactory.getLogger(SendMailUtil.class);




    //private static JavaMailSender javaMailSender = SpringBeanUtil.getBean(JavaMailSenderImpl.class);

    private static final Properties instance;


    private SendMailUtil() {
        if (instance != null) {
            throw new IllegalStateException();
        }
    }
    static {
        instance = new Properties();
        instance.setProperty("mail.transport.protocol","smtp");
        instance.setProperty("mail.smtp.host","smtp.qq.com");
        instance.setProperty("mail.smtp.auth","true");
        instance.setProperty("mail.smtp.port","587");
        instance.setProperty("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
        instance.setProperty("mail.smtp.socketFactory.fallback","false");
        instance.setProperty("mail.smtp.socketFactory.port","587");
    }

    public static final Properties getInstance() {

        return instance;
    }


    /**
     * 纯文本
     *
     * @param subject 标题
     * @param content 内容
     * @param from    发件人
     * @param to      收件人
     */
    public static void sendSimpleMail(String subject, String content, String from, String[] to) {
        try {
            Session session = commonProperties();
            JavaMailSender mailSender =new JavaMailSenderImpl();
            MimeMessage message =mailSender.createMimeMessage();
            MimeMessageHelper helper =new MimeMessageHelper(message,true);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content);
            helper.setFrom(from);
            Transport transport = commonCommit(session);
            transport.sendMessage(message,message.getAllRecipients());
        } catch (Exception e) {
            e.printStackTrace();
        }
        //发送邮件
        //javaMailSender.send(mailMessage);
        Log.info("邮件发送成功,subject:{},form:{},to:{}", subject, from, to);
    }


    /**
     * 图片
     *
     * @param subject
     * @param content 带有html代码
     * @param from
     * @param to
     * @throws MessagingException
     */
    public static void sendHtmlMail(String subject, String content, String from, String[] to) {
        try {
            Session session = commonProperties();
            JavaMailSender javaMailSender=new JavaMailSenderImpl();
            Log.info("要发邮件了!");
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            //是否发送的邮件是富文本(附件,图片,html等)
            MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true, "utf-8");
            messageHelper.setFrom(from);
            messageHelper.setTo(to);
            messageHelper.setSubject(subject);
            //重点,默认为false,显示原始html代码,无效果;为true时可识别html代码,有效果
            messageHelper.setText(content, true);
            //发送邮件
            Log.info("发送邮件开始!"+from);
            Transport transport = commonCommit(session);
            transport.sendMessage(mimeMessage,mimeMessage.getAllRecipients());
        } catch (Exception e) {
            e.printStackTrace();
        }
        //javaMailSender.send(mimeMessage);
        //Log.info("邮件发送成功,subject:{},form:{},to:{},content:{}", subject, from, to, content);
    }



    /**
     * 附件
     *
     * @param subject
     * @param content
     * @param attachmentMap
     * @param from
     * @param to
     * @throws MessagingException
     */
    public static void sendAttachmentMail(String subject, String content, String from, String[] to, Map<String, String> attachmentMap) {
        try {
            Session session = commonProperties();
            JavaMailSender javaMailSender=new JavaMailSenderImpl();
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            //是否发送的邮件是富文本(附件,图片,html等)
            MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true, "utf-8");
            messageHelper.setFrom(from);
            messageHelper.setTo(to);
            messageHelper.setSubject(subject);
            //重点,默认为false,显示原始html代码,无效果
            messageHelper.setText(content);
            if (attachmentMap != null) {
                attachmentMap.entrySet().stream().forEach(entrySet -> {
                    try {
                        File file = new File(entrySet.getValue());
                        if (file.exists()) {
                            messageHelper.addAttachment(entrySet.getKey(), new FileSystemResource(file));
                        }
                    } catch (MessagingException e) {
                        e.printStackTrace();
                    }
                });
            }
            Transport transport = commonCommit(session);
            transport.sendMessage(mimeMessage,mimeMessage.getAllRecipients());
            //发送邮件
            transport.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        Log.info("邮件发送成功,subject:{},form:{},to:{}", subject, from, to);
    }

    /**
     * 附件2------流式发送
     *
     * @param subject
     * @param content
     * @param from
     * @param to
     * @param inputStreamSource
     * @param fileName
     * @throws MessagingException
     */
    public static void sendAttachmentMail2(String subject, String content, String from, String[] to, InputStreamSource inputStreamSource, String fileName) {
        try {
            JavaMailSender javaMailSender=new JavaMailSenderImpl();

            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            //是否发送的邮件是富文本(附件,图片,html等)
            MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true, "utf-8");
            messageHelper.setFrom(from);
            messageHelper.setTo(to);
            messageHelper.setSubject(subject);
            //重点,默认为false,显示原始html代码,无效果
            messageHelper.setText(content);
            messageHelper.addAttachment(fileName,inputStreamSource);
            //发送邮件
            javaMailSender.send(mimeMessage);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
        Log.info("邮件发送成功,subject:{},form:{},to:{}", subject, from, to);
    }


    public static boolean isEmail(String email) {
        if (null == email || "".equals(email)) {
            return false;
        }
        String regEx1 = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
        Pattern p = Pattern.compile(regEx1);
        Matcher m = p.matcher(email);
        if (m.matches()) {
            return true;
        } else {
            return false;
        }
    }

    @Test
    public void test() throws Exception {
        String msg = "986125495@qq.com";
        System.out.println(isEmail(msg));
        String[] s = {"986125495@qq.com"};
        Map<String,String> map=new HashMap<>();
        map.put("path","D:\\D1-OCR(1).pdf");
        //sendAttachmentMail("测试发送","这是一条测试数据","986125495@qq.com",s,map);
        sendSimpleMail("测试","这是个测试数据","986125495@qq.com",s);
    }


  public static Session commonProperties(){
      Properties instance = getInstance();
      // 2. 根据配置创建会话对象, 用于和邮件服务器交互
      Session session = Session.getDefaultInstance(instance);
      session.setDebug(true);
      return session;
  }

  public static Transport commonCommit(Session session) throws Exception {
      // 4. 根据 Session 获取邮件传输对象
      Transport transport = session.getTransport();

      // 5. 使用 邮箱账号 和 密码 连接邮件服务器, 这里认证的邮箱必须与 message 中的发件人邮箱一致, 否则报错
      //
      //    PS_01: 成败的判断关键在此一句, 如果连接服务器失败, 都会在控制台输出相应失败原因的 log,
      //           仔细查看失败原因, 有些邮箱服务器会返回错误码或查看错误类型的链接, 根据给出的错误
      //           类型到对应邮件服务器的帮助网站上查看具体失败原因。
      //
      //    PS_02: 连接失败的原因通常为以下几点, 仔细检查代码:
      //           (1) 邮箱没有开启 SMTP 服务;
      //           (2) 邮箱密码错误, 例如某些邮箱开启了独立密码;
      //           (3) 邮箱服务器要求必须要使用 SSL 安全连接;
      //           (4) 请求过于频繁或其他原因, 被邮件服务器拒绝服务;
      //           (5) 如果以上几点都确定无误, 到邮件服务器网站查找帮助。
      //
      //    PS_03: 仔细看log, 认真看log, 看懂log, 错误原因都在log已说明。
      transport.connect("XXXXX", "XXXXXX");

      return transport;

  }
}

上一篇:hive第五天


下一篇:MySQL 索引篇