springboot JavaMailSender发送带html格式的邮件和普通文本邮件

导入依赖


            org.springframework.boot
            spring-boot-starter-mail
        

yml配置:

spring:
    mail:
    host: smtp.qq.com
    username: ********@qq.com
    password: **********
    properties:
      mail:
        smtp:
          auth: true
          starttls:
            enable: true
            required: true
    port: 587

方法

@RestController
public class UserController{
    @Autowired
    private UserRepositories userRepositories;
    @Autowired
    private JavaMailSender javaMailSender;

    @Value("${spring.mail.username}")
    private String from;

    /**
     *@Author: ZongMao on 2020/4/2 20:11
     *发送简单文本邮件
     *@return
     */
    public void sendSimpleMail(String mailTo, String mailHead, String mailContent) throws Exception {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(mailTo);
        message.setSubject(mailHead);
        message.setText(mailContent);
        javaMailSender.send(message);
    }

    /**
     *@Author: ZongMao on 2020/4/2 20:11
     *发送html文本邮件
     *@return
     */
    public void sendHtmlMail(String mailTo,String mailHead,String mailContent) throws Exception{
        MimeMessage mimeMailMessage = this.javaMailSender.createMimeMessage();
        try {
            MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMailMessage,true,"utf-8");
            messageHelper.setFrom(from);
            messageHelper.setTo(mailTo);
            messageHelper.setSubject(mailHead);
            messageHelper.setText(mailContent,true);
           javaMailSender.send(mimeMailMessage);

        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }

    /**
     * @return
     * @Author: ZongMao on 2020/2/18 18:48
     * 发送注册验证码
     */
    @CrossOrigin(allowCredentials = "true", allowedHeaders = "*")
    @PostMapping("/sendVCode")
    public String sendVCode(String email, HttpSession session, VCode oldCode) {
//        随机生成6位数的纯数字验证码
        String code = new Random().nextInt(900000) + 100000 + "";
        if (userRepositories.findByEmail(email) != null) {
            return "email";
        } else {
//            在session中存入验证码和有效期
//            定义一个vCode存放 VCode(验证码), ETime(过期时间);
//            把上面的这个vCode保存到session中;  session.setAttribute("registerVCode", vCode);
//            从session中取出这个vCode,将vCode中的get属性,和用户输入的验证码提交的时间进行相比,如果小于expiredDate(过期时间),则在有效时间之类,进一步对用户输入的验证码进行比较。;
            oldCode.setVCode(code);
            oldCode.setEmail(email);
            oldCode.setETime(new Date().getTime());
            session.setAttribute("registerVCode", oldCode);
        }
        try {
            sendSimpleMail(email, "浙校园注册验证码", "[浙校园]" + "你的注册码为:  " + code + "   ,有效期2分钟,如果非本本人操作,请忽视");
        } catch (Exception e) {
            return "发送失败";
        }
        return "发送成功";
    }


    /**
     * @return
     * @Author: ZongMao on 2020/2/20 15:20
     * 随机生成字符串方法
     */
    //length用户要求产生字符串的长度
    public String getRandomString(int length) {
        String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(62);
            sb.append(str.charAt(number));
        }
        return sb.toString();
    }

    @CrossOrigin(allowCredentials = "true", allowedHeaders = "*")
    @PostMapping("/sendChangePdLink")
    public String sendChangePdLink(String email,String urlHost) {
        String changePdLink = getRandomString(20);
        if (userRepositories.findByEmail(email) == null) {
            return "email";
        } else {
            userRepositories.setChangPdLink(email, changePdLink);
        }
        try {
            String link ="http://"+urlHost+"/resetPd?email="+email+"&changePwLink=" + changePdLink;
//            sendSimpleMail(email, "浙校园修改密码", "[浙校园]" + "您正在申请修改密码,请复制此链接到浏览器访问进行修改:" + link + "此链接有效期为一次,请勿泄露给他人造成隐私和财产安全!如果非本本人操作,请忽视!");
            sendHtmlMail(email,"浙校园修改密码","[浙校园] 您正在申请修改密码,请点击此链接访问进行修改:"+"修改密码"+"此链接有效期为一次,请勿泄露给他人造成隐私和财产安全!如果非本本人操作,请忽视!");
        } catch (Exception e) {
            return "发送失败";
        }
        return "发送成功";
    }
}

 

你可能感兴趣的:(java,spring,boot)