springboot integrated mail quick start demo

HBLOG
4 min readFeb 29, 2024

--

一、introduction

in daily work development, we need to develop send mail function. here First let me introduce some protocols related to sending and receiving emails:

  • send:SMPT、MIME,is a protocols base on ”push”,through SMPT protocols send mail to mail server,MIME protocol is a supplement to SMPT protocol, such as sending picture attachments, etc.
  • receivie:POP、IMAP,It is a “pull”-based protocol. The recipient pulls the email from the mail server through the POP protocol.

二、 prepare

Gmail client configuration description :refer to official Gmail help

三、Code Project

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>springboot-demo</artifactId>
<groupId>com.et</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>mail</artifactId>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
</dependencies>
</project>

application.properties

#here we take qq as an example
# qq mail server
spring.mail.host=smtp.qq.com
# you qq mail username
spring.mail.username=yourAccount@qq.com
# third token
spring.mail.password=yourPassword
# code Type
spring.mail.default-encoding=UTF-8
spring.thymeleaf.prefix=classpath:/template/

DemoApplication.java

package com.et.mail;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}

MailUtil.java

package com.et.mail.util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
/**
* @author zhaokuii11@163.com
* @create 2022-01-11 19:22
* @Description
*/
@Service
public class MailUtils {
// log
private final Logger logger = LoggerFactory.getLogger(MailUtils.class);
@Value("${spring.mail.username}")
private String from;
@Autowired
private JavaMailSender mailSender;

/**
* send txt
*
* @param to
* @param subject
* @param content
*/
public void sendSimpleMail(
String to, String subject, String content
) {
SimpleMailMessage message = new SimpleMailMessage();
message.setTo(to);
message.setSubject(subject);
message.setText(content);
message.setFrom(from);
mailSender.send(message);
}
/**
* send html mail
*
* @param to
* @param subject
* @param content
*/
public void sendHtmlMail(
String to, String subject, String content
) {
//use MimeMessage,MIME protocol
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper;
//MimeMessageHelper help us to set more configuration
try {
helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(content, true);
mailSender.send(message);
logger.info("send HTML email success");
} catch (MessagingException e) {
e.printStackTrace();
logger.error("send HTML email fail:", e);
}
}

/**
* send mail with attachments
*
* @param to
* @param subject
* @param content
* @param filePath
*/
public void sendAttachmentMail(
String to, String subject,
String content, String filePath
) {
// log
logger.info("send starting:{},{},{},{}", to, subject, content, filePath);
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper;
try {
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 = file.getFilename();
helper.addAttachment(fileName, file);/
mailSender.send(message);
logger.info("send email success");
} catch (MessagingException e) {
logger.error("send email fail", e);
}
}
/**
* send mail with pictures
*
* @param to
* @param subject
* @param content
* @param rscPath
* @param rscId rscId
*/
public void sendInlineResourceMail(
String to, String subject, String content,
String rscPath, String rscId) {
// 日志
logger.info("send staring:{},{},{},{},{}", to, subject, content, rscPath, rscId);
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper;
try {
helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(content, true);
FileSystemResource res = new FileSystemResource(new File(rscPath));
helper.addInline(rscId, res);/
mailSender.send(message);
logger.info("send email success");
} catch (MessagingException e) {
logger.error("send email fail", e);
}
}
}

email template

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>mail template</title>
</head>
<body>
hello,thank you for your register,this is a validate email,please click the link and finish the regsiter,thank you for your support!<br>
<a href="#" th:href="@{http://www.bestbpf.com/register/{id}(id=${id})}">active account</a>
</body>
</html>

Code repository

四、test

package com.et;
import com.et.mail.DemoApplication;
import com.et.mail.util.MailUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
/**
* @author zhaokuii11@163.com
* @create 2022-01-11 19:49
* @Description
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = DemoApplication.class)
public class SpringBootApplicationTest {
@Autowired
MailUtils mailUtils;
@Autowired
private TemplateEngine templateEngine;


@Test
public void testTemplateMail() {

Context context = new Context();
context.setVariable("id", "001");
String emailContent = templateEngine.process("emailTemplate", context);
mailUtils.sendHtmlMail("zhaokuii11@163.com", "this is a template file", emailContent);
}
/**
* send text email
*/
@Test
public void sendSimpleMail() {
mailUtils.sendSimpleMail("zhaokuii11@163.com", "send email test", "hi,this is springboot send mail");
}
/**
* send HTML mail
*/
@Test
public void sendHtmlMail() {
String content = "<html><body><h3><font color=\"red\">" + "hi,this is springboot send HTML mail" + "</font></h3></body></html>";
mailUtils.sendHtmlMail("zhaokuii11@163.com", "send email test", content);
}
/**
* send mail with attachments
*/
@Test
public void sendAttachmentMail() {
String content = "<html><body><h3><font color=\"red\">" + "hi,this is springboot send HTML mail,have attachments" + "</font></h3></body></html>";
String filePath = "your file path";
mailUtils.sendAttachmentMail("zhaokuii11@163.com", "send email test", content, filePath);
}
/**
* send email with pictures
*/
@Test
public void sendInlineResourceMail() {
String rscPath = "your picture path";
String rscId = "001";
String content = "<html><body><h3><font color=\"red\">" + "hi,this is springboot send HTML mail,have pictutes" + "</font></h3>"
+ "<img src=\'cid:" + rscId + "\'></body></html>";
mailUtils.sendInlineResourceMail("zhaokuii11@163.com", "send email test", content, rscPath, rscId);
}
}

五、reference

--

--

HBLOG
HBLOG

Written by HBLOG

talk is cheap ,show me your code

No responses yet