Springboot2邮件发送

1.引入Jar包;

        <!--Mail-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>
        <dependency>
            <groupId>com.sun.mail</groupId>
            <artifactId>javax.mail</artifactId>
            <version>1.6.2</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>5.0.13.RELEASE</version>
        </dependency>

2.application.properties文件中配置Mail参数;

#发送邮件服务器
spring.mail.host=smtp.qq.com
spring.mail.username=xxx@qq.com
#客户端授权码
spring.mail.password=xxx
#发送邮件协议
spring.mail.protocol=smtp
spring.mail.properties.mail.smtp.auth=true
#端口号465或587
spring.mail.properties.mail.smtp.port=465
spring.mail.properties.mail.display.sendmail=Javen
spring.mail.properties.mail.display.sendname=Spring Boot Guide Email
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
spring.mail.properties.mail.smtp.connectiontimeout=5000
spring.mail.properties.mail.smtp.timeout=3000
spring.mail.properties.mail.smtp.writetimeout=5000
#启动ssl
spring.mail.properties.mail.smtp.ssl.enable=true
spring.mail.default-encoding=utf-8
#同username
spring.mail.from=xxx

3.接口

public interface MailService {
    /**
     * 发送文本邮件
     * @param to
     * @param subject
     * @param content
     */
    VO sendSimpleMail(String to, String subject, String content);
    /**
     * 批量发送文本邮件
     * @param to
     * @param subject
     * @param content
     */
    VO sendSimpleMail(String to, String subject, String content, String... cc);

    /**
     * 发送带附件的邮件
     * @param to
     * @param subject
     * @param content
     * @param filePath
     * @throws MessagingException
     */
    VO sendAttachmentsMail(String to, String subject, String content, String filePath);

    /**
     * 发送HTML邮件
     * @param to
     * @param subject
     * @param content
     * @throws MessagingException
     */
    VO sendHtmlMail(String to, String subject, String content);

    VO sendHtmlMail(String to, String subject, String content, String... cc);
}

4.接口实现

@Service
public class MailServiceImpl implements MailService {

    @Autowired
    private JavaMailSender mailSender;
    @Value("${spring.mail.from}")
    private String from;

    @Override
    public VO sendSimpleMail(String to, String subject, String content) {
        VO vo = VoUtil.successVO("邮件发送成功");
        try {
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(from);
            message.setTo(to);
            message.setSubject(subject);
            message.setText(content);
            mailSender.send(message);
        }catch (Exception e){
            System.out.println(e);
            vo = VoUtil.failVO("邮件发送失败");
        }
        return vo;
    }

    @Override
    public VO sendSimpleMail(String to, String subject, String content, String... cc) {
        VO vo = VoUtil.successVO("邮件发送成功");
        try {
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(from);
            message.setTo(to);
            message.setCc(cc);
            message.setSubject(subject);
            message.setText(content);
            mailSender.send(message);
        }catch (Exception e){
            System.out.println(e);
            vo = VoUtil.failVO("邮件发送失败");
        }
        return vo;
    }

    @Override
    public VO sendAttachmentsMail(String to, String subject, String content, String filePath) {
        VO vo = VoUtil.successVO("邮件发送成功");
        try {
            MimeMessage message = mailSender.createMimeMessage();

            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);

            FileSystemResource file = new FileSystemResource(new File(filePath));
            String fileName = filePath.substring(filePath.lastIndexOf(File.separator));
            helper.addAttachment(fileName, file);

            mailSender.send(message);
        }catch (Exception e){
            System.out.println(e);
            vo = VoUtil.failVO("邮件发送失败");
        }
        return vo;
    }

    @Override
    public VO sendHtmlMail(String to, String subject, String content){
        return null;
    }

    @Override
    public VO sendHtmlMail(String to, String subject, String content, String... cc) {
        return null;
    }

}

5.测试

@Controller
@RequestMapping("/demo/")
public class EmailController {

    @Autowired
    MailService mailService;

    @RequestMapping("sendSimpleMail")
    @ResponseBody
    public VO sendSimpleMail(){
        return this.mailService.sendSimpleMail("xxx@qq.com","SpringBoot Email","这是一封普通的SpringBoot测试邮件");
    }
}

6.注意事项

如果项目使用了ehcache缓存,再引入spring-context-support的时候,由于support中也包含了ehcache,项目启动时,会报如下错误:

Caused by: net.sf.ehcache.CacheException: Another CacheManager with same name 'BASE_EHCACHE' already exists in the same VM. Please provide unique names for each CacheManager in the config or do one of following:
1. Use one of the CacheManager.create() static factory methods to reuse same CacheManager with same name or create one if necessary
2. Shutdown the earlier cacheManager before creating new one with same name.
The source of the existing CacheManager is: InputStreamConfigurationSource [stream=java.io.ByteArrayInputStream@da8b48e]

可以通过如下配置来解决问题:

@Bean
public EhCacheManagerFactoryBean ehCacheManagerFactoryBean() {
    EhCacheManagerFactoryBean ehCacheManagerFactoryBean = new EhCacheManagerFactoryBean();
    ehCacheManagerFactoryBean.setShared(true);
    return ehCacheManagerFactoryBean;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值