This is the 19th day of my participation in the August More Text Challenge

Email configuration

  1. pom.xml

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-mail</artifactId>
    </dependency>
    <! Use thymeleaf to parse the template -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    Copy the code
  2. application.yaml

    spring:
      mail:
        host: smtp.qq.com
        port: 465
        username: [email protected]
        password: caifdytfhvaqdiif
        protocol: smtp
        test-connection: true
        default-encoding: UTF-8
        properties:
          mail.smtp.auth: true
          mail.smtp.ssl.enable: true
          mail.smtp.starttls.enable: true
          mail.smtp.starttls.required: true
    Copy the code

The simple mail

  1. Utility methods

    public interface MailService {
        void sendSimpleMail(String to, String subject, String content, String... cc);
    }
    
    @Service
    public class MailServiceImpl implements MailService {
    
        @Autowired
        private JavaMailSender mailSender;
        @Value("${spring.mail.username}")
        private String from;
    
        @Override
        public void sendSimpleMail(String to, String subject, String text, String... cc) {
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(from);
            message.setTo(to);
            message.setSubject(subject);
            message.setText(text);
            if(ArrayUtil.isEmpty(cc)) { message.setCc(cc); } mailSender.send(message); }}Copy the code
  2. Method of use

    @SpringBootTest
    class MailTests {
        @Autowired
        MailService mailService;
    
        @Test
        void sendSimpleMail(a) throws Exception {
            mailService.sendSimpleMail("[email protected]"."Title"."Test content"); }}Copy the code

Template mail

  1. Utility methods

    public interface MailService {
        void sendTempLateMail(String to, String subject, String content, String... cc) throws MessagingException;
    }
    
    @Service
    public class MailServiceImpl implements MailService {
    
        @Autowired
        private JavaMailSender mailSender;
        @Value("${spring.mail.username}")
        private String from;
    
        @Override
        public void sendTempLateMail(String to, String subject, String content, String... cc) throws MessagingException {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            // Parse to HTML
            helper.setText(content, true);
            if(ArrayUtil.isEmpty(cc)) { helper.setCc(cc); } mailSender.send(message); }}Copy the code
  2. Method of use

    @SpringBootTest
    class MailTests {
        @Autowired
        MailService mailService;
        // Thymeleaf template parsing tool
        @Autowired
        private TemplateEngine templateEngine;
        // Set templateResolver
        @Autowired
        private ApplicationContext context;
    
     	@Test
        void sendTemplateMail(a) throws Exception {
            SpringResourceTemplateResolver templateResolver 
                = new SpringResourceTemplateResolver();
            templateResolver.setApplicationContext(context);
            templateResolver.setCacheable(false);
            templateResolver.setPrefix("classpath:/email/");
            templateResolver.setSuffix(".html");
            templateEngine.setTemplateResolver(templateResolver);
    
            Context context = new Context();
            context.setVariable("name"."Cade");
            context.setVariable("age"."23");
            context.setVariable("sex"."boy");
    
            // If templateResolver is not used, the default is the HTML file in the templates folder
            String emailTemplate = templateEngine.process("test", context);
            mailService.sendTempLateMail("[email protected]"."Template mail", emailTemplate); }}Copy the code

With the attachment

  1. Utility methods

    public interface MailService {
        void sendAttachmentsMail(String to, String subject, String content, String filePath, String... cc) throws MessagingException;
    }
    
    @Service
    public class MailServiceImpl implements MailService {
    
        @Autowired
        private JavaMailSender mailSender;
        @Value("${spring.mail.username}")
        private String from;
    
        @Override
        public void sendAttachmentsMail(String to, String subject, String content, String filePath, String... cc) throws MessagingException {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);
            if (ArrayUtil.isEmpty(cc)) {
                helper.setCc(cc);
            }
            FileSystemResource file = new FileSystemResource(new File(filePath));
            // Use the URL object getPath to return the path/without using file.separator
            String fileName = filePath.substring(filePath.lastIndexOf("/")); helper.addAttachment(fileName, file); mailSender.send(message); }}Copy the code
  2. Method of use

    @SpringBootTest
    class MailTests {
        @Autowired
        MailService mailService;
        @Autowired
        private TemplateEngine templateEngine;
        @Autowired
        private ApplicationContext context;	
    	
        @Test
        void sendAttachmentsMail(a) throws MessagingException {
            URL resource = this.getClass().getResource("/static/img.jpg");
            mailService.sendAttachmentsMail("[email protected]"."Attached Mail"."Please check the attachment in the email!", resource.getPath()); }}Copy the code

Static resource

  1. Utility methods

    public interface MailService {
        void sendAttachmentsMail(String to, String subject, String content, String filePath, String... cc) throws MessagingException;
    }
    
    @Service
    public class MailServiceImpl implements MailService {
    
        @Autowired
        private JavaMailSender mailSender;
        @Value("${spring.mail.username}")
        private String from;
    
        @Override
        public void sendResourceMail(String to, String subject, String content, String resourcePath, String contentId, String... cc) throws MessagingException {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);
            if (ArrayUtil.isNotEmpty(cc)) {
                helper.setCc(cc);
            }
            FileSystemResource res = new FileSystemResource(newFile(resourcePath)); helper.addInline(contentId, res); mailSender.send(message); }}Copy the code
  2. Method of use

        @Test
        public void sendResourceMail(a) throws MessagingException {
            String contentId = "cade";
            // Cid of the img tag :contentId is used to replace placeholders
            String content = "<html>" +
                    "<body>" +
                    "Carrying messages with static resources 

    "
    + "<img src=\'cid:" + contentId + "\' >" + "</body>" + "</html>"; URL resource = this.getClass().getResource("/static/img.jpg"); mailService.sendResourceMail("[email protected]"."Static Resource Mail", content, resource.getPath(), contentId); } Copy the code

Third-party tools

  1. Hutool’s MailUtil utility class encapsulates Javax. mail

    Pom.xml introduces javax.mail and hutool-extra or hutool-all

    <dependency>
        <groupId>javax.mail</groupId>
        <artifactId>mail</artifactId>
        <version>1.4.7</version>
    </dependency>
    <dependency>
        <groupId>cn.hutool</groupId>
        <artifactId>hutool-extra</artifactId>
        <version>5.4.5</version>
    </dependency>
    Copy the code

    The resource/config/mail. Setting the configuration file

    # SMTP address of the mail server, optional, default is SMTP.
    host = smtp.yeah.net
    The SMTP port of the mail server is optional. Default is 25
    port = 25
    # the sender
    from = [email protected]
    The default user name is the sender email prefix
    user = hutool
    # password, some email addresses need to be set to authorization code
    pass = xxxx
    Copy the code

    use

    MailUtil.send("[email protected]"."Test"."Mail Test".false);
    Copy the code

    Sending an email is very simple. There is only one method to do it. The parameters are described as follows:

    1. Tos: Email address of the other party, which can be single or multiple (Collection)
    2. Subject: title
    3. Content: Indicates the email body, which can be text or HTML
    4. IsHtml: whether it isHtml or not, if so, then parameter 3 identifies it as HTML content
    5. Files: Optional: Attachment, can be multiple or none, add File object to the last variable argument