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
[email protected]
#客戶端授權碼
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("[email protected]","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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章