目录
引入依赖
配置文件配置
具体代码
MultipartFile 转 File 工具类
org.springframework.boot
spring-boot-starter-mail
log4j
log4j
1.2.17
org.slf4j
slf4j-log4j12
1.7.25
test
org.slf4j
slf4j-api
1.7.25
cn.hutool
hutool-all
5.8.12
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
@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 list = new ArrayList<>();
for (Iterator 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() + "", 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("邮件正文模板 \n" +
"\n" +
"\n" +
"\n" +
"周星星:
\n" +
"\n" +
"人生的成功有千百种,您用劳动书写光荣,您用真情善待家人!今天是您的生日,请把心放松,静静地聆听我们的祝福:快乐、健康、幸福。\n" +
"
\n" +
"" + time + "
\n" +
"\n" +
"\n" +
"");
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;
}
}
}
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 随笔