1.MAVEN依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
2.yml配置文件
spring:
mail:
#设置邮箱服务器/端口
host: smtp.exmail.qq.com
port: 465
#设置邮箱用户名
username: xxx@xx.com
#设置邮箱密码
password: xxx123456
properties:
mail:
smtp:
auth: true
starttls:
enable: true
required: true
ssl:
enable: true
default-encoding: utf-8
3.发送实现类
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.UrlResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.net.MalformedURLException;
@Service
public class EmailService {
@Resource
private JavaMailSender mailSender;
@Value("${spring.mail.username}")
private String from;
/**
* 发送附件到邮箱
* @param to 邮箱地址
* @param subject 邮件主题
* @param text 内容
* @param attachmentName 附件名称
* @param attachmentUrl 附件地址
* @throws MessagingException
* @throws MalformedURLException
*/
public void sendEmailWithAttachment(String to, String subject, String text, String attachmentName, String attachmentUrl) throws MessagingException, MalformedURLException {
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(text);
UrlResource resource = new UrlResource(attachmentUrl);
helper.addAttachment(attachmentName, resource);
mailSender.send(message);
}
}
@GetMapping("sendAttachment")
public void sendAttachment(@Param("toEmail") String toEmail) {
// 创建 URL 对象
try {
String attachmentUrl = "https://xxxx.com/测试文件.zip";
String attachmentName = "测试主题";
String subject = "测试测试";
String text = "测试邮件内容";
emailService.sendEmailWithAttachment("xxx@xx.com", subject, text, attachmentName, attachmentUrl);
} catch (Exception e) {
throw new RuntimeException(e);
}
}