background

A friend asked me how you used to email. So I found him a demo, and I wrote it here to share it with you.

Clarify pain points

Send mail, you can think about, where is the pit? I think it’s three. First: the issue of email whitelist. Second: email timeout problem. Third: mail with attachment problem. The following demo will introduce these problems and solutions.

Implementation scheme

The preparatory work

We need to have an email address that we can send to, so I’m going to use my email address, 163, as an example. Now, the rules for sending an email require you to enter something called an authorization code, which is not a password. The procedure for obtaining an authorization code is as follows:

The SpringBoot project introduces mail packages

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

Yml Configure mail related

spring:
  mail:
    # Mail service address
    host: smtp.163.com
    # Port, not default
    port: 25
    # Code format
    default-encoding: utf-8
    # username
    username: [email protected]
    # Authorization code is the code we just prepared to get
    password: xxx
    # Other parameters
    properties:
      mail:
        smtp:
          If SSL mode is used, the following attributes need to be configured. If QQ mailbox is used, it needs to be enabled
          ssl:
            enable: true
            required: true
          # Time limit for receiving emails, in milliseconds
          timeout: 10000
          # Connection time limit, in milliseconds
          connectiontimeout: 10000
          The time limit for sending emails, in milliseconds
          writetimeout: 10000
Copy the code

For the timeout problem mentioned above, catching the timeout exception solves the problem.

Mail sending tool class

The need to send Java mail can be met primarily with the following utility classes. Once we’ve done the YML configuration, SpringBoot will help us automatically configure the JavaMailSender which is a Java class that we can use to manipulate Java to send mail. Here is a list of some common emails.

@Service public class MailService { private static final Logger logger = LoggerFactory.getLogger(MailServiceImpl.class);  @Autowired private JavaMailSender mailSender; private static final String SENDER ="[email protected]"; /** * Send regular mail ** @param to recipient * @param Subject subject * @param Content */ @override public void sendSimpleMailMessge(String to, String subject, String content) { SimpleMailMessage message = new SimpleMailMessage(); message.setFrom(SENDER); message.setTo(to); message.setSubject(subject); message.setText(content); try { mailSender.send(message); } catch (Exception e) { logger.error("An exception occurred while sending a simple email!", e); }} /** * Send an HTML email ** @param to the recipient ** @param Subject * @param Content */ @override public void sendMimeMessge(String to, String subject, String content) { MimeMessage message = mailSender.createMimeMessage(); try { //trueMimeMessageHelper = new MimeMessageHelper(message,true);
            helper.setFrom(SENDER);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);
            mailSender.send(message);
        } catch (MessagingException e) {
            logger.error("An exception occurred while sending MimeMessge!", e); }} /** * Sending emails with attachments ** @param to recipient * @param Subject subject * @param Content * @param filePath Attachment path */ @override public void sendMimeMessge(String to, String subject, String content, String filePath) { MimeMessage message = mailSender.createMimeMessage(); try { //trueMimeMessageHelper = new MimeMessageHelper(message,true);
            helper.setFrom(SENDER);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);

            FileSystemResource file = new FileSystemResource(new File(filePath));
            String fileName = file.getFilename();
            helper.addAttachment(fileName, file);

            mailSender.send(message);
        } catch (MessagingException e) {
            logger.error("An exception occurred while sending MimeMessge with attachments!", e); }} /** * Send an email with a static file ** @param to the recipient ** @param Subject * @param Content * @param rscIdMap Static file to be replaced */ @override public void sendMimeMessge(String to, String subject, String content, Map<String, String> rscIdMap) { MimeMessage message = mailSender.createMimeMessage(); try { //trueMimeMessageHelper = new MimeMessageHelper(message,true);
            helper.setFrom(SENDER);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);

            for (Map.Entry<String, String> entry : rscIdMap.entrySet()) {
                FileSystemResource file = new FileSystemResource(new File(entry.getValue()));
                helper.addInline(entry.getKey(), file);
            }
            mailSender.send(message);
        } catch (MessagingException e) {
            logger.error("An exception occurred while sending MimeMessge with static files!", e); }}}Copy the code

Demo for sending emails

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbooEmailDemoApplicationTests {

    @Autowired
    private MailService mailService;

    private static final String TO = "[email protected]";
    private static final String SUBJECT = "Test mail";
    private static final String CONTENT = "test content"; /** * Test sending snail mail */ @test public voidsendSimpleMailMessage() { mailService.sendSimpleMailMessge(TO, SUBJECT, CONTENT); } /** * Test to send HTML messages */ @test public voidsendHtmlMessage() {
        String htmlStr = "<h1>Test</h1>"; mailService.sendMimeMessge(TO, SUBJECT, htmlStr); } /** * Testing sending emails with attachments * @throws FileNotFoundException */ @test public void sendAttachmentMessage() throws FileNotFoundException { File file = ResourceUtils.getFile("classpath:test.txt"); String filePath = file.getAbsolutePath(); mailService.sendMimeMessge(TO, SUBJECT, CONTENT, filePath); } /** * Testing sending emails with attachments * @throws FileNotFoundException */ @test public void sendPicMessage() throws FileNotFoundException { String htmlStr ="< HTML > < body > test: picture 1 < br > < img SRC = \ 'cid: pic1 \' / > < br > 2 < br > < img SRC = \ 'cid: pic2 \' / > < / body > < / HTML >";
        Map<String, String> rscIdMap = new HashMap<>(2);
        rscIdMap.put("pic1", ResourceUtils.getFile("classpath:pic01.jpg").getAbsolutePath());
        rscIdMap.put("pic2", ResourceUtils.getFile("classpath:pic02.jpg").getAbsolutePath()); mailService.sendMimeMessge(TO, SUBJECT, htmlStr, rscIdMap); }}Copy the code

White list problem

If the email is sent to a fixed email address, you can directly set a whitelist in the fixed email address. If the email is frequently sent to multiple email addresses, you are advised to set the following sending interval. Do not continuously send the email to a certain email address.

conclusion

So far, SpringBoot email introduction is finished, you can directly use the code to send.