SpringBoot send mail from multiple email sources

Keywords: Programming Spring encoding Database

preface

                                .

Realization ideas

Spring boot starter mail will spring.mail.xxx The related configuration automatically configures JavaMailSender. But only a single mailbox is supported. To implement multiple mail sources, you can refer to the above logic. Configured in the configuration file, multiple mail sources. Then read the configuration file, manually configure the JavaMailSender, and initialize it in the JavaMailSender storage container. Then take out JavaMailSender randomly to send.

Introduce dependency

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

Mail yml configuration

Replace the actual mail configuration

# Configure mail
mail:
  configs:
    # account number
    - username: fapiao@QQ.com
      password: 123456
      host: smtp.qq.com
      port: 25
      protocol: smtp
      default-encoding: UTF-8
    # Account A
    - username: fapiaoa@QQ.com
      password: 123456
      host: smtp.qq.com
      port: 25
      protocol: smtp
      default-encoding: UTF-8

MailConfig

@Data
@Component
@ConfigurationProperties(prefix = "mail")
public class MailConfig {

    private List<MailProperties> configs;

    @Data
    public static class MailProperties {

        /**
         * password
         */
        private String username;

        /**
         * password
         */
        private String password;

        /**
         * host
         */
        private String host;

        /**
         * port
         */
        private Integer port;

        /**
         * agreement
         */
        private String protocol;

        /**
         * Default encoding
         */
        private String defaultEncoding;

    }

}

MailSenderConfig

@Slf4j
@Component
@AllArgsConstructor
public class MailSenderConfig {

    private final MailConfig mailConfig;

    private final List<JavaMailSenderImpl> senderList;

    /**
     * Initialize sender
     */
    @PostConstruct
    public void buildMailSender(){
        List<MailConfig.MailProperties> mailConfigs = mailConfig.getConfigs();
        log.info("initialization mailSender");
        mailConfigs.forEach(mailProperties -> {

            // Email Sender 
            JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
            javaMailSender.setDefaultEncoding(mailProperties.getDefaultEncoding());
            javaMailSender.setHost(mailProperties.getHost());
            javaMailSender.setPort(mailProperties.getPort());
            javaMailSender.setProtocol(mailProperties.getProtocol());
            javaMailSender.setUsername(mailProperties.getUsername());
            javaMailSender.setPassword(mailProperties.getPassword());

            // Add data
            senderList.add(javaMailSender);
        });
    }

    /**
     * Get MailSender
     * @return CustomMailSender
     */
    public JavaMailSenderImpl getSender(){
        if(senderList.isEmpty()){
            buildMailSender();
        }
        // Random return of a JavaMailSender
        return senderList.get(new Random().nextInt(senderList.size()));
    }

    /**
     * Clean up sender
     */
    public void clear(){
        senderList.clear();
    }

}

MailService

public interface MailService {

    /**
     * Send mail
     * @return Return true or false
     */
    boolean sendMail();

}

MailServiceImpl

@Service
@AllArgsConstructor
public class MailServiceImpl implements MailService {

    private final MailSenderConfig senderConfig;

    @Override
    public boolean sendMail() {

        JavaMailSenderImpl mailSender = senderConfig.getSender();

        //Create a SimpleMailMessage object
        SimpleMailMessage message = new SimpleMailMessage();
        //Email sent by
        message.setFrom(Objects.requireNonNull(mailSender.getUsername()));
        //Mail recipient
        message.setTo("2583174414@qq.com");
        //Message subject
        message.setSubject("Test mail");
        //Message content
        message.setText("Test message content");
        //Send mail
        mailSender.send(message);

        return true;
    }
}

test

@SpringBootTest
@RunWith(SpringRunner.class)
class MailServiceImplTest {

    @Autowired
    private MailServiceImpl mailService;

    @Test
    void sendMail() {
        mailService.sendMail();
    }
}

test result

Points of attention

  • You need to check whether the related protocol of mailbox configuration is enabled.
  • If QQ email is used for sending, the password is not the email password, but the authorization code.

expand

   the above is to write the mailbox configuration to the configuration file. Without using the configuration center, if the mailbox source is limited, it will be relatively troublesome to change. The configuration can be stored in the database and loaded from the database at startup. If the mailbox source changes, you can change the database mailbox source configuration directly, and then call it. MailSenderConfig.clear() method, the configuration will be reinitialized when waiting for the next sending.

ending

                          .

Posted by Xyox on Tue, 16 Jun 2020 01:11:25 -0700