Gitee link
Spring Boot version: 2.3.4.RELEASE
Send a mail reference link
Send SMS reference links
It is necessary to prepare for sending emails and short messages. In this paper, QQ mailbox is used as the sender, and SMTP should be enabled. Short credit is Ali cloud, to create a good signature and approved SMS template, the main content of this article code module, the preparation of these two services is not introduced.
Originally, the mailbox used 163, but the email sent by 163 mailbox kept prompting 554, no matter how to modify, so WE had to change to QQ.
Importing Maven dependencies
<! -- Send email -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<! -- Send SMS -->
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-core</artifactId>
<version>4.5.1</version>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-dysmsapi</artifactId>
<version>1.1.0</version>
</dependency>
Copy the code
Then there is the configuration file application:
server:
port: 8888
spring:
mail:
host: smtp.qq.com # Mail service address
username: Filling them in # sender email
password: Filling them in # authorization code
default-encoding: UTF-8 The default message encoding is UTF-8
properties:
mail:
smtp:
auth: true
# If SSL is used, the following attributes need to be configured. If QQ email is used, the following attributes need to be enabled
starttls:
enable: true
required: true
sms:
accessKeyId: Filling them in
accessSecret: Filling them in
signName: Filling them in
templateCode: Filling them in
Copy the code
Send E-mail
There are many types of email: plain text, HTML, with attachments, content with images.
package com.cc.service;
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;
import java.util.Map;
/** ** Mail service *@author cc
* @dateIn 2021-12-07 he * /
@Service
public class MailService {
private final JavaMailSender mailSender;
@Value("${spring.mail.username}")
private String SENDER;
public MailService(JavaMailSender mailSender) {
this.mailSender = mailSender;
}
// Send regular mail
public void sendSimpleMailMessage(String to, String subject, String content) {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(SENDER);
message.setTo(to);
message.setSubject(subject);
message.setText(content);
mailSender.send(message);
}
// Send HTML mail
public void sendMimeMessage(String to, String subject, String content) throws MessagingException {
MimeMessage message = mailSender.createMimeMessage();;
// true indicates that a multipart message needs to be created
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(SENDER);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(content, true);
mailSender.send(message);
}
// Send mail with attachments
public void sendMimeMessage(String to, String subject, String content, String filePath) throws MessagingException {
MimeMessage message = mailSender.createMimeMessage();;
// true indicates that a multipart message needs to be created
MimeMessageHelper helper = 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);
}
// Send mail with static files
public void sendMimeMessage(String to, String subject, String content, Map<String,String> rscIdMap) throws MessagingException {
MimeMessage message = mailSender.createMimeMessage();
// true indicates that a multipart message needs to be created
MimeMessageHelper helper = 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(newFile(entry.getValue())); helper.addInline(entry.getKey(), file); } mailSender.send(message); }}Copy the code
Send a text message
package com.cc.service;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
/** * SMS service **@author cc
* @dateThe 2021-12-07 will * /
@Service
public class SmsService {
@Value("${sms.accessKeyId}")
private String accessKeyId;
@Value("${sms.accessSecret}")
private String accessSecret;
@Value("${sms.signName}")
private String signName;
@Value("${sms.templateCode}")
private String templateCode;
public void send(String phone, String code) throws ClientException {
if (StringUtils.isEmpty(phone)) {
throw new RuntimeException("Cell phone number cannot be empty.");
}
if (StringUtils.isEmpty(code)) {
throw new RuntimeException("Verification code cannot be empty.");
}
// Initialize acsClient. Regionalization is not supported
IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou",
accessKeyId, accessSecret);
IAcsClient acsClient = new DefaultAcsClient(profile);
// Assemble the request object - see the console - documentation section for details
SendSmsRequest request = new SendSmsRequest();
// Required: Mobile phone number to be sent
request.setPhoneNumbers(phone);
// Required: SMS signature - can be found in SMS console
request.setSignName(signName);
// Required: SMS template - Available in the SMS console
request.setTemplateCode(templateCode);
request.setTemplateParam("{\"code\":\"" + code + "\"}");
SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
if(sendSmsResponse.getCode()! =null && "OK".equals(sendSmsResponse.getCode())){
System.out.println("SMS sent successfully!");
}else {
throw new RuntimeException("SMS sending failed:"+ sendSmsResponse.getMessage()); }}}Copy the code
Generate captcha
package com.cc.utils;
import java.util.Random;
/** * Captcha generator *@author cc
* @dateThe 2021-12-07 yea * /
public class VerifyCodeGenerator {
public static String make(int length) {
if (length <= 0) {
throw new RuntimeException("Verification code length cannot be less than 1");
}
StringBuilder sb = new StringBuilder();
Random random = new Random();
for (int i = 0; i < length; i++) {
sb.append(random.nextInt(10));
}
returnsb.toString(); }}Copy the code
Test the
PNG, pic02.png, and test. TXT files should be added to resources in advance to facilitate testing
The test class:
package com.cc;
import com.aliyuncs.exceptions.ClientException;
import com.cc.service.MailService;
import com.cc.service.SmsService;
import com.cc.utils.VerifyCodeGenerator;
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.springframework.util.ResourceUtils;
import javax.mail.MessagingException;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Map;
@SpringBootTest
@RunWith(SpringRunner.class)
public class ApplicationTest {
// Test cannot have a parameter constructor
@Autowired
private MailService mailService;
@Autowired
private SmsService smsService;
private static final String TO = "[email protected]";
private static final String SUBJECT = "Show me the way";
private static final String CONTENT = "The first emperor did not venture half and the collapse of the middle way intelligently, today the next three points, Yizhou exhausted, this is the autumn of critical survival. However, the minister of the bodyguard unremitting in the inside, loyal to the people forget the body in the outside, cover chasing the emperor's special encounter, want to repay to your Majesty. Sincerity should open holy listen, to light first emperor left de, the grand spirit of the gas, should not be self-deprecation, citing metaphor injustice, to plug the road of loyal remonstrance. \n" +
"Palace in the palace, all as one, the punishment zang whether, should not be different. If there are wrongdoers and those who are loyal and virtuous, they should be punished with punishment, so as to demonstrate your Majesty's plain principle and not to be biased and make internal and external laws different.";
// Test sending plain mail
@Test
public void sendSimpleMailMessage(a) {
mailService.sendSimpleMailMessage(TO, SUBJECT, CONTENT);
}
// Test sending HTML mail
@Test
public void sendHtmlMessage(a) throws MessagingException {
String htmlStr = "<h1>Test</h1>";
mailService.sendMimeMessage(TO, SUBJECT, htmlStr);
}
// Test sending mail with attachments
@Test
public void sendAttachmentMessage(a) throws FileNotFoundException, MessagingException {
File file = ResourceUtils.getFile("classpath:test.txt");
System.out.println(file);
String filePath = file.getAbsolutePath();
mailService.sendMimeMessage(TO, SUBJECT, CONTENT, filePath);
}
// Test sending mail with static files
@Test
public void sendStaticFileMessage(a) throws FileNotFoundException, MessagingException {
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.png").getAbsolutePath());
rscIdMap.put("pic2", ResourceUtils.getFile("classpath:pic02.png").getAbsolutePath());
mailService.sendMimeMessage(TO, SUBJECT, htmlStr, rscIdMap);
}
// Test sending SMS messages
@Test
public void sendSms(a) throws ClientException {
smsService.send("your phone", VerifyCodeGenerator.make(6));
}
// Generate a verification code
@Test
public void generatorVerifyCode(a) {
System.out.println(VerifyCodeGenerator.make(4)); }}Copy the code
Email and SMS sending is still very simple, are modulated interface.
Note that there is a charge for using text messages. The current price is 0.045 cents.