1.发送简单文本邮件
1)导入jar包
<dependency>
<groupId>javax.mail</groupId>
<artifactId>javax.mail-api</artifactId>
<version>1.6.2</version>
</dependency>
<dependency>
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
<version>1.1.1</version>
</dependency>
2)上代码
package com.test;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
public class SendEmail {
public static void SendEmail(String sendAddress, String title, String content, String copysendAddress) throws MessagingException {
Properties properties = new Properties();
// 设置服务器名称
properties.setProperty("mail.host","smtp.qq.com");
// 设置文件传输协议
properties.setProperty("mail.transport.protocol", "smtp");
// 设置是否要验证服务器用户名和密码
properties.setProperty("mail.smtp.auth", "true");
// 1.创建客户端与邮箱服务器的Session对象
Session session = Session.getInstance(properties);
// 2.开启 session 的 debug 模式,方便查看发送 email 的运行状态
session.setDebug(true);
// 3.通过 session 得到 transport 传输对象
Transport transport = session.getTransport();
// 4.使用用户名、授权码连接上邮箱服务器,此处的授权码需要到邮箱开启服务设置
transport.connect("smtp.qq.com","xxx@qq.com","xxx");// 授权码
// 5.创建邮件
Message message = createSimpleMail(session, sendAddress ,title, content, copysendAddress);
// 6.发送邮件
transport.sendMessage(message, message.getAllRecipients());
transport.close();
}
private static Message createSimpleMail(Session session, String sendAddress, String title, String content, String copysendAddress) throws MessagingException {
// 创建邮件对象
MimeMessage message = new MimeMessage(session);
// 指明邮件的发件人
message.setFrom(new InternetAddress("xxx@qq.com"));
// 指明邮件的收件人
message.setRecipient(Message.RecipientType.TO, new InternetAddress(sendAddress));
// 邮件的标题
message.setSubject(title);
// 邮件的内容
message.setContent(content, "text/html;charset=UTF-8");
// 设置抄送人
message.setRecipients(Message.RecipientType.CC, InternetAddress.parse(copysendAddress));
return message;
}
public static void main(String[] args) throws MessagingException {
SendEmail("xxx@qq.com", "邮件发送演示", "邮件内容", "xxx2@qq.com");
}
}
2.SpringBoot JavaMailSender发送html文本、附件邮件
https://blog.csdn.net/zongmaomx/article/details/105278668
https://blog.csdn.net/qq_31281189/article/details/97760951
2.1 SpringBoot使用JavaMailSender发送普通文本邮件
application.yml配置
# 发送邮件
spring:
mail:
# 邮箱账号
username: xxx@qq.com
# 操作码
password: xxx
host: smtp.qq.com
1)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">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.4</version>
</parent>
<groupId>com.yu</groupId>
<artifactId>spring-test01</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
2)model
package com.yu.model;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Email {
private String title;
private String content;
private String to;
}
3)Controller
package com.yu.controller;
import com.yu.model.Email;
import com.yu.service.EmailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.mail.MessagingException;
@RestController
@RequestMapping("/test")
public class TestController {
@Autowired
private EmailService emailService;
@RequestMapping("sendEmail")
public String sendEmail() throws MessagingException {
Email email = new Email();
email.setTo("xxx@qq.com");
email.setTitle("发邮件测试003");
email.setContent("发邮件测试内容003");
emailService.sendEmail(email);
return "ok";
}
}
4)Service
package com.yu.service;
import com.yu.model.Email;
import javax.mail.MessagingException;
public interface EmailService {
public void sendEmail(Email email) throws MessagingException;
}
5)ServiceImpl
package com.yu.service.impl;
import com.yu.model.Email;
import com.yu.service.EmailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
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;
@Service
public class EmailServiceImpl implements EmailService {
@Autowired
private JavaMailSender javaMailSender;
@Value("${spring.mail.username}")
private String fromEmail;
public void sendEmail(Email email) throws MessagingException {
// 1.创建一个MimeMessage
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
// 2.发送邮件的一个工具类
MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage);
mimeMessageHelper.setTo(email.getTo());
mimeMessageHelper.setSubject(email.getTitle());
mimeMessageHelper.setText(email.getContent());
mimeMessageHelper.setFrom(fromEmail);
javaMailSender.send(mimeMessage);
}
}
6)单元测试
package com.yu;
import com.yu.model.Email;
import com.yu.service.EmailService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import javax.mail.MessagingException;
@SpringBootTest
public class sendEmailTest {
// 能正常注册bean
@Autowired
private EmailService emailService;
@Test
public void Test() throws MessagingException {
Email email = new Email();
email.setTo("xxx@qq.com");
email.setTitle("发邮件测试006");
email.setContent("发邮件测试内容006");
emailService.sendEmail(email);
}
}
2.2 .xlsx附件(待完成)
package com.yu.service.impl;
import com.yu.model.Email;
import com.yu.service.EmailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
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;
@Service
public class EmailServiceImpl implements EmailService {
@Autowired
private JavaMailSender javaMailSender;
@Value("${spring.mail.username}")
private String fromEmail;
public void sendEmail(Email email) throws MessagingException {
// 1.创建一个MimeMessage
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
// 2.发送邮件的一个工具类
MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage);
mimeMessageHelper.setTo(email.getTo());
mimeMessageHelper.setSubject(email.getTitle());
mimeMessageHelper.setText(email.getContent(), true);
mimeMessageHelper.setFrom(fromEmail);
MultipartFile multipartFile = createWorkbookAndConvertMultipartFile(email.getTitles(), eamil.getList());
mimeMessageHelper.addAttachment(email.getFileName(), multipartFile);
javaMailSender.send(mimeMessage);
}
/*
* 将数据生成 Workbook 并转成 MultipartFile
*
* @param titles
* @param MultipartFile
*/
public MultipartFile createWorkbookAndConvertMultipartFile(String titles[], List<String> list) {
//簿
Workbook workbook = new SXSSFWorkbook();
//表
Sheet sheet = workbook.createSheet();
// 写title
Row row0 = sheet.createRow(0);
for (int i = 0; i < titles.length; i++) {
Cell cell = row0.createCell(i);
cell.setCellValue(titles[i]);
}
// 写数据(省略)
MultipartFile multipartFile = null;
try {
ByteArrayOutputStream oup = new ByteArrayOutputStream();
workbook.write(oup);
byte[] bytes = oup.toByteArray();
InputStream inputStream = new ByteArrayInputStream(bytes);
multipartFile = new MockMultipartFile("name", "name", "name", inputStream);
oup.close();
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
// 清除临时文件
((SXSSFWorkbook) workbook).dispose();
long end = System.currentTimeMillis();
System.out.println((double) (end - begin) / 1000);
return multipartFile;
}
}