目录
[MultipartFile 转 File 工具类](#MultipartFile 转 File 工具类)
引入依赖
XML
<!--邮件-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<!--日志-->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.25</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.25</version>
</dependency>
<!--工具集-->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.12</version>
</dependency>
配置文件配置
java
spring:
servlet:
multipart:
max-file-size: 10MB
max-request-size: 50MB
mail:
host: #填写邮箱服务器地址
port: 465 #服务器端口
username: #发件人邮箱号
password: #邮箱登录密码,或授权码
default-encoding: utf-8
protocol: smtp #邮件协议
test-connection: true
properties:
mail:
# 是否发送正文
mime:
multipart:
allowempty: true
smtp:
ssl:
enable: true
starttls:
enable: true
required: true
# connectiontimeout: 10000 #建立连接时间限制
# timeout: 10000 #邮件接收时间限制
# wridtetimeout: 10000 #邮件发送时间限制
auth: true
具体代码
java
@Service
public class MailService {
private Logger logger = LoggerFactory.getLogger(getClass());//提供日志类
@Autowired
private JavaMailSenderImpl javaMailSender;
/*public JavaMailSenderImpl createJavaMailSender(JavaMailSenderImpl javaMailSender) { //依赖注入报红线时可以试试,不管也可以用
return this.javaMailSender = new JavaMailSenderImpl();
}*/
public boolean sendMail(Mail mail) {
try {
/*没有传入发件人,设置默认*/
if (StrUtil.isEmpty(mail.getFrom()))
mail.setFrom("邮箱号");
/* 邮箱号为这种形式时可用该方法,获取别名和邮箱号
mail.setFrom("\"别名\" <邮箱号>");
InternetAddress internetAddress = new InternetAddress(mail.getFrom());
邮箱号 别名
mimeMessageHelper.setFrom(internetAddress.getAddress(), internetAddress.getPersonal());
*/
/*没有发件人或收件人*/
if (StrUtil.isEmpty(mail.getFrom()) || StrUtil.isEmpty(mail.getTo()))
return false;
/*创建邮件*/
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);//true:识别html格式
/*发件人*/
mimeMessageHelper.setFrom(mail.getFrom());
/*收件人*/
if (mail.getTo().contains(",") || mail.getTo().contains(",")) {
String[] split = null;
/*判断收件人邮箱号并拆分*/
if (mail.getTo().contains(","))
split = mail.getTo().split(",");
if (mail.getTo().contains(","))
split = mail.getTo().split(",");
/*放入 InternetAddress 类型的list*/
ArrayList<InternetAddress> list = new ArrayList<>();
for (Iterator<String> iterator = Arrays.stream(split).iterator(); iterator.hasNext(); ) {
list.add(new InternetAddress(iterator.next()));
}
/*转 InternetAddress 数组*/
InternetAddress[] addresses = list.toArray(new InternetAddress[list.size()]);
mimeMessageHelper.setTo(addresses);
} else
mimeMessageHelper.setTo(mail.getTo());
/*发送时间*/
mimeMessageHelper.setSentDate(new Date());
/*主题*/
mimeMessageHelper.setSubject(mail.getSubject());
/*正文*/
if (mail.getFiles() != null) {
/*正文包含图片*/
int i = 0;
for (MultipartFile multipartFile : mail.getFiles()) {
++i;
mimeMessageHelper.setText(mail.getText() + "<div><img src='cid:" + i + "'/></div>", true);
File file = multipartFileToFile.multipartFileToFiles(multipartFile);/* MultipartFile 转 File */
mimeMessageHelper.addInline(StrUtil.toString(i), new FileSystemResource(file));
}
} else
mimeMessageHelper.setText(mail.getText());
/*正文需发送html时*/
/*
String property = System.getProperty("user.dir");//获取当前项目路径
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日");
String time = simpleDateFormat.format(System.currentTimeMillis());
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append("<!DOCTYPE html><html lang=\"en\"><head><meta charset=\"UTF-8\"><title>邮件正文模板</title></head><body>\n" +
"<div style=\"margin:0 auto;width:700px;height:500px\">\n" +
"<img src=\"cid:background.jpg\" style=\"width: 700px;\"/>\n" +
"<div style=\"margin:-600px 80px 0 170px;font-size:20px;\">\n" +
"<p style=\"color:mediumvioletred;\">周星星:</p>\n" +
"<p style=\"color:deeppink;\">\n" +
"人生的成功有千百种,您用劳动书写光荣,您用真情善待家人!今天是您的生日,请把心放松,静静地聆听我们的祝福:快乐、健康、幸福。\n" +
"</p>\n" +
"<p id=\"date\" style=\"text-align:right;margin-right: 100px\">" + time + "</p>\n" +
"</div>\n" +
"</div>\n" +
"</body></html>");
mimeMessageHelper.setText(stringBuffer.toString(), true);
mimeMessageHelper.addInline("background.jpg", new File(property + "/src/main/resources/img/background.jpg"));
*/
/*附件*/
if (mail.getMultipartFiles() != null) {
for (MultipartFile multipartFile : mail.getMultipartFiles()) {
mimeMessageHelper.addAttachment(multipartFile.getOriginalFilename(), multipartFile);
}
}
/*发送*/
javaMailSender.send(mimeMessage);
logger.info("发送成功:{}--->{}", mail.getFrom(), mail.getTo());
return true;
} catch (Exception e) {
e.printStackTrace();
logger.debug("发送失败:{}--->{}", mail.getFrom(), mail.getTo());
return false;
}
}
}
MultipartFile 转 File 工具类
java
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
@Component
public class MultipartFileToFile {
/**
* MultipartFile 转 File
*
* @param file
* @throws Exception
*/
public File multipartFileToFiles(MultipartFile file) throws Exception {
File toFile = null;
if (file.equals("") || file.getSize() <= 0) {
file = null;
} else {
InputStream ins = null;
ins = file.getInputStream();
toFile = new File(file.getOriginalFilename());
inputStreamToFile(ins, toFile);
ins.close();
}
return toFile;
}
//获取流文件
private void inputStreamToFile(InputStream ins, File file) {
try {
OutputStream os = new FileOutputStream(file);
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.close();
ins.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 删除本地临时文件
*
* @param file
*/
public void delteTempFile(File file) {
if (file != null) {
File del = new File(file.toURI());
del.delete();
}
}
}
Cheung Kwok Wing 随笔