JavaMail,顾名思义,提供给开发者处理电子邮件相关的编程接口。它是Sun发布的用来处理email的API。它可以方便地执行一些常用的邮件传输。我们可以基于JavaMail开发出类似于Microsoft Outlook的应用程序。
Quick Start
properties配置文件
#-------------邮件服务器信息-------------------
mail.smtp.auth=true
mail.smtp.timeout=25000
mail.smtp.starttls.enable=false
ywt.email.host=mail.xxx.com
ywt.email.port=25
ywt.email.from=zhangianbo@xxx.com
ywt.email.username=xxx
ywt.email.password=yyy
添加maven依赖:poi、javamail
spring配置文件
<bean id="javaMailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="javaMailProperties">
<props>
<prop key="mail.smtp.auth">${mail.smtp.auth}</prop>
<prop key="mail.smtp.timeout">${mail.smtp.timeout}</prop>
<prop key="mail.smtp.starttls.enable">${mail.smtp.starttls.enable}</prop>
<!-- <prop key="mail.smtp.socketFactory.class">javax.net.ssl.SSLSocketFactory</prop> -->
</props>
</property>
</bean>
EmailSendDto
/**
* @author zhangjianbo
* @date 2018/2/23
*/
@Data
@NoArgsConstructor
public class EmailSendDto implements Serializable{
private String from;
private String to;
private String subject;
private String text;
/**
* zip压缩包文件名
*/
private String zipFileName;
/**
* 是否批量发送
*/
private Boolean isBatch=false;
/**
* 是否有附件
*/
private Boolean multipart=false;
/**
* csv文件名列表
*/
private List<String> fileNameList=new ArrayList<>();
/**
* csv文件表头
*/
private List<String[]> headerList=new ArrayList<>();
/**
* csv文件数据
*/
private List<List<String[]>> dataList=new ArrayList<>();
}
EmailService
/**
* @author zhangjianbo
* @date 2018/2/22
*/
public interface EmailService {
/**
* 发送邮件
* @param emailSendDto
* @return
*/
EmailSendResultDto send(EmailSendDto emailSendDto);
}
EmailServiceImpl
/**
*
* @author zhangjianbo
* @date 2018/2/22
*/
@Service("emailServiceImpl")
public class EmailServiceImpl implements EmailService{
@Resource(name = "javaMailSender")
private JavaMailSenderImpl javaMailSender;
@Value("${ywt.email.host}")
private String emailHost;
@Value("${ywt.email.port}")
private String emailPort;
@Value("${ywt.email.username}")
private String userName;
@Value("${ywt.email.password}")
private String password;
@Value("${ywt.email.from}")
private String from;
private static final String EXCEL=".xls";
@Override
public EmailSendResultDto send(EmailSendDto emailSendDto) {
EmailSendResultDto sendResultDto = new EmailSendResultDto();
try {
javaMailSender.setHost(emailHost);
javaMailSender.setPort(Integer.valueOf(emailPort));
javaMailSender.setUsername(userName);
javaMailSender.setPassword(password);
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
MimeMessageHelper mimeMessageHelper;
if (emailSendDto.getMultipart()) {
mimeMessageHelper = new MimeMessageHelper(mimeMessage, true, "utf-8");
}else{
mimeMessageHelper = new MimeMessageHelper(mimeMessage, false, "utf-8");
}
mimeMessageHelper.setFrom(from);
mimeMessageHelper.setTo(emailSendDto.getTo());
mimeMessageHelper.setSubject(emailSendDto.getSubject());
mimeMessageHelper.setText(emailSendDto.getText(), true);
if(!emailSendDto.getMultipart()){
javaMailSender.send(mimeMessage);
sendResultDto.setSendStatus(EmailSendStatus.SUCCESS);
}else{
List<String> tempExcelFilePathList = new ArrayList<>();
File zipFile = null;
File directory =null;
try {
String directoryPath = System.getProperty("java.io.tmpdir") + File.separator + UUID.randomUUID();
directory = new File(directoryPath);
if (!directory.exists()) {
directory.mkdir();
}
for (int i = 0; i < emailSendDto.getHeaderList().size(); i++) {
String[] header = emailSendDto.getHeaderList().get(i);
List<String[]> dataList = emailSendDto.getDataList().get(i);
String excelFileName=emailSendDto.getFileNameList().get(i);
//1.向临时路径写入excel文件
String excelFilePath = directoryPath + File.separator + excelFileName + EXCEL;
try {
Workbook wb=new HSSFWorkbook();
Sheet sheet=wb.createSheet(excelFileName);
sheet.setDefaultColumnWidth(20);
sheet.setDefaultRowHeightInPoints(20);
//写入表头
Row rowHeader=sheet.createRow(0);
for(int k=0;k<header.length;k++){
Cell cell=rowHeader.createCell(k);
cell.setCellValue(header[k]);
}
//写入内容
for (int t = 0; t < dataList.size(); t++) {
Row rowData=sheet.createRow(t+1);
String[] data = dataList.get(t);
for(int w=0;w<data.length;w++){
Cell cell=rowData.createCell(w);
cell.setCellValue(data[w]);
}
}
FileOutputStream fileOut=new FileOutputStream(excelFilePath);
wb.write(fileOut);
fileOut.close();
System.out.println("--------EXCEL文件写入成功--------");
tempExcelFilePathList.add(excelFilePath);
} catch (IOException ex) {
System.out.println("--------EXCEL文件写入失败--------");
ex.printStackTrace();
}
}
if (tempExcelFilePathList.size() == 1) {
File file = new File(tempExcelFilePathList.get(0));
mimeMessageHelper.addAttachment(MimeUtility.encodeWord(emailSendDto.getFileNameList().get(0))+EXCEL, file);
} else {
String zipFileName = emailSendDto.getZipFileName();
ZipOutputStream outStream = new ZipOutputStream(new FileOutputStream(zipFileName));
for (int n = 0; n < tempExcelFilePathList.size(); n++) {
String csvPath = tempExcelFilePathList.get(n);
File file = new File(csvPath);
FileInputStream inStream = new FileInputStream(file);
outStream.putNextEntry(new ZipEntry(emailSendDto.getFileNameList().get(n)));
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inStream.read(buffer)) > 0) {
outStream.write(buffer, 0, bytesRead);
}
inStream.close();
}
outStream.closeEntry();
outStream.close();
zipFile = new File(zipFileName);
mimeMessageHelper.addAttachment(MimeUtility.encodeWord(zipFileName), zipFile);
}
javaMailSender.send(mimeMessage);
sendResultDto.setSendStatus(EmailSendStatus.SUCCESS);
} catch (IOException ex) {
sendResultDto.setSendStatus(EmailSendStatus.FAIL);
sendResultDto.setErrMsg(ex.getMessage());
} finally {
//3.删除临时文件
for (int m = 0; m < tempExcelFilePathList.size(); m++) {
File file = new File(tempExcelFilePathList.get(m));
if (file.exists() && file.isFile()) {
try {
file.delete();
} catch (Exception e) {
System.out.println("删除csv临时文件失败");
}
}
}
if (zipFile != null) {
try {
zipFile.delete();
} catch (Exception ex) {
System.out.println("删除zip临时文件失败");
}
}
if(directory!=null) {
try {
directory.delete();
} catch (Exception ex) {
System.out.println("删除临时目录失败");
}
}
}
}
} catch (MessagingException e) {
sendResultDto.setSendStatus(EmailSendStatus.FAIL);
sendResultDto.setErrMsg(e.getMessage());
} catch (Exception ex2) {
sendResultDto.setSendStatus(EmailSendStatus.FAIL);
sendResultDto.setErrMsg(ex2.getMessage());
}
return sendResultDto;
}
}
调用Example
EmailSendDto sendDto=new EmailSendDto();
//邮件主题
sendDto.setSubject("XXX-报表");
//邮件内容
sendDto.setText("XXX-报表");
//附件名称列表
sendDto.getFileNameList().add("XXX-报表");
//附件表头
sendDto.getHeaderList().add(new String[]{"姓名","年龄","性别"});
//附件数据(与/附件名称/表头要一一对应)
List<String[]> dataList=new ArrayList();//获取具体数据
sendDto.getDataList().add(dataList);
Boolean res=emailService.send(sendDto,currentSalesman);
if(res){
return ResultWrapperFactory.toSuccess("发送成功");
}else{
return ResultWrapperFactory.toError("发送失败");
}