1.需要的依赖
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
2. Util
import org.apache.poi.util.IOUtils; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.io.ByteArrayResource; import org.springframework.mail.javamail.JavaMailSenderImpl; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.stereotype.Service; import javax.mail.Session; import javax.mail.internet.MimeMessage; import java.io.InputStream; import java.util.List; import java.util.Map; import java.util.Properties; @Service public class EmailUtil { @Value("${email.host}") private String host; @Value("${email.from}") private String from; @Value("${email.password}") private String password; /** * 发送邮件工具类 * * @param tos * @param subject * @param emailContent * @param isHtml * @throws Exception */ public void send(List<String> tos, String subject, String emailContent, boolean isHtml, Map<String, InputStream> attachments) throws Exception { generalSend(host, password, from, tos, subject, emailContent, isHtml, attachments); } private void generalSend(String host, String password, String from, List<String> tos, String subject, String emailContent, boolean isHtml, Map<String, InputStream> attachments) throws Exception { JavaMailSenderImpl senderImpl = new JavaMailSenderImpl(); //设定mail server senderImpl.setHost(host); //建立邮件消息,发送简单邮件和html邮件的区别 MimeMessage mailMessage = senderImpl.createMimeMessage(); MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage, 1, "UTF-8"); //设置收件人,寄件人 messageHelper.setTo(tos.toArray(new String[]{})); messageHelper.setFrom(from); messageHelper.setSubject(subject); //true 表示启动HTML格式的邮件 messageHelper.setText(emailContent, isHtml); //添加文件文件 if (attachments != null && attachments.size() > 0) { for (String fileName : attachments.keySet()) { InputStream in = attachments.get(fileName); ByteArrayResource bar = new ByteArrayResource(IOUtils.toByteArray(in)); messageHelper.addAttachment(fileName, bar); } } //设置邮箱属性 Properties prop = new Properties(); // 将这个参数设为true,让服务器进行认证,认证用户名和密码是否正确 prop.put("mail.smtp.auth", "true"); prop.put("mail.smtp.starttls.enable", "true"); prop.put("mail.smtp.host", host); prop.put("mail.smtp.user", from); prop.put("mail.smtp.pass", password); //配置发送类信息 senderImpl.setJavaMailProperties(prop); senderImpl.setUsername(from); senderImpl.setPassword(password); senderImpl.setSession(Session.getDefaultInstance(senderImpl.getJavaMailProperties())); //发送邮件 senderImpl.send(mailMessage); } }