1. Introduce dependencies
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
Copy the code
2. Find qq mailbox, open SMTP service, here to generate your password, copy the third step to use
3. Enter the password you obtained in the password (important: this must be correct)
[email protected]
spring.mail.password=********
spring.mail.host=smtp.qq.com
Enable encryption authentication
spring.mail.properties.mail.smtp.ssl.enable=true
Copy the code
EmailApplicationTests class, contextLoads are simple to send, contextLoads are limited to text. ContextLoads2 is complex and can send images in HTML format
package com.xyj;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
@SpringBootTest
class EmailApplicationTests {
@Autowired
JavaMailSenderImpl mailSender;
@Test
void contextLoads() {
SimpleMailMessage mailMessage = new SimpleMailMessage();
mailMessage.setSubject("Hello");
mailMessage.setText("123456");
mailMessage.setTo("[email protected]");
mailMessage.setFrom("[email protected]");
mailSender.send(mailMessage);
}
@Test
void contextLoads2() throws MessagingException {
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true);
helper.setSubject("Hello");
helper.setText(".true);
helper.addAttachment("bg.jpg",new File("D:\ money\ web \ epidemic \images\ bg1.jpg"));
helper.setTo("[email protected]");
helper.setFrom("[email protected]"); mailSender.send(mimeMessage); }}Copy the code