获取对应邮箱的密钥

以qq邮箱为例:qq邮箱的相关配置可以参考该链接

与SpringBoot整合

简单发送邮件

引入依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
</dependency>

编写配置类

@Configuration
public class EmailConfig {

    @Bean
    public JavaMailSender javaMailSender(){
        int port = 465;

        JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
        javaMailSender.setHost("smtp.qq.com");
        javaMailSender.setUsername("xxxxxx@qq.com"); //用户名
        javaMailSender.setPassword("xxxx-xxxx-xxxx"); //密钥
        javaMailSender.setDefaultEncoding("utf-8");

        // 配置端口和ssl(使用在阿里云和本地环境)
        Properties properties = new Properties();
        properties.setProperty("mail.smtp.auth", "true");//开启认证
        properties.setProperty("mail.smtp.timeout", "1000");//设置链接超时
        properties.setProperty("mail.smtp.port", Integer.toString(port));//设置端口
        properties.setProperty("mail.smtp.socketFactory.port", Integer.toString(port));//设置ssl端口
        properties.setProperty("mail.smtp.socketFactory.fallback", "false");
        properties.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        javaMailSender.setJavaMailProperties(properties);
        return javaMailSender;
    }

}

简单的发送邮件

@Service
public class EmailService {
    @Autowired
    private JavaMailSender mailSender;//注入邮件工具类

    // 发送邮箱
    public void sendEmail(String html) {
        try {
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mailSender.createMimeMessage(), false);
            mimeMessageHelper.setFrom("xxxx@qq.com");
            mimeMessageHelper.setTo("xxxx@qq.com");
            mimeMessageHelper.setSubject("邮件主题");
  
            mimeMessageHelper.setText(html,true);//邮件内容
            mailSender.send(mimeMessageHelper.getMimeMessage());//正式发送邮件
        } catch (MessagingException e) {
            throw new RuntimeException("邮件发送异常");
        }
    }

}

开启异步发送邮件

添加异步配置类,并开启异步注解

@Slf4j
@EnableAsync //开启异步
@Configuration
public class AsyncConfig implements AsyncConfigurer {

    @Override
    public Executor getAsyncExecutor() {
        return new ThreadPoolExecutor(
                3, //核心线程数
                8, //最大线程数
                30, //超时时间
                TimeUnit.SECONDS, //超时时间单位
                new ArrayBlockingQueue<>(1000),//存放任务的阻塞队列
                new ThreadPoolExecutor.AbortPolicy());//传入默认的拒绝策略(当任务被拒绝时抛出RejectedExecutionException异常)
    }

    // 异常处理
    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return (throwable, method, objects) -> {
            log.error("异步任务处理异常",throwable);//记录一下日志
        };
    }
}

使用@Async注解开启异步发送

@Service
public class EmailService {
    @Autowired
    private JavaMailSender mailSender;//注入邮件工具类

    // 开启异步发送通知邮件
    @Async
    public void sendEmail(String html) {
        try {
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mailSender.createMimeMessage(), false);
            mimeMessageHelper.setFrom("xxxx@qq.com");
            mimeMessageHelper.setTo("xxxx@qq.com");
            mimeMessageHelper.setSubject("邮件主题");
  
            mimeMessageHelper.setText(html,true);//邮件内容
            mailSender.send(mimeMessageHelper.getMimeMessage());//正式发送邮件
        } catch (MessagingException e) {
            throw new RuntimeException("邮件发送异常");
        }
    }

}

使用Freemarker模版定制邮件内容

在Service中注入Freemarker的配置类,并指定模版渲染成html发送即可

@Service
public class EmailService {
    @Autowired
    private JavaMailSender mailSender;//注入邮件工具类

    @Autowired
    private Configuration configuration;//freemarker配置

    // 开启异步发送通知邮件
    @Async
    public void sendEmail(String html) {
        try {
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mailSender.createMimeMessage(), false);
            mimeMessageHelper.setFrom("xxxx@qq.com");
            mimeMessageHelper.setTo("xxxx@qq.com");
            mimeMessageHelper.setSubject("邮件主题");
  
            // 通过freemarker渲染
            Template template = configuration.getTemplate("tool/email.ftl");//获取模版
            Map<String, Object> model = new HashMap<>();
            model.put("xxxx", "yyyy");// 添加属性
            String html = FreeMarkerTemplateUtils.processTemplateIntoString(template,model);//渲染模版

            mimeMessageHelper.setText(html,true);//邮件内容
            mailSender.send(mimeMessageHelper.getMimeMessage());//正式发送邮件
        } catch (MessagingException e) {
            throw new RuntimeException("邮件发送异常");
        }
    }

}
0条评论
头像
ICP证 : 浙ICP备18021271号