poi的介绍我就不多说了,详情见:
https://blog.csdn.net/fz13768884254/article/details/82706936
https://blog.csdn.net/fz13768884254/article/details/82703959
代码如下:
import base.BaseTest;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.junit.Test;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.InputStreamSource;
import javax.annotation.Resource;
import javax.mail.MessagingException;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
/**
* @description: 测试发送邮件
* @author: fengze
* @create: 2018-04-13 21:25
**/
public class TestEmail extends BaseTest {
@Resource
private JavaMailSenderImpl javaMailSender;
@Resource
private EmailConfig emailConfig;
@Test
public void sendMailWithExcel() throws IOException, MessagingException {
String[] headers = {"col1","col2","col3"};
// 声明一个工作薄
HSSFWorkbook wb = new HSSFWorkbook();
// 生成一个表格
HSSFSheet sheet = wb.createSheet();
HSSFRow row = sheet.createRow(0);
for (int i = 0; i < headers.length; i++) {
HSSFCell cell = row.createCell(i);
cell.setCellValue(headers[i]);
}
int rowIndex = 1;
for(int j=0; j<3; j++){
row = sheet.createRow(rowIndex);
rowIndex++;
HSSFCell cell1 = row.createCell(0);
cell1.setCellValue(j);
cell1 = row.createCell(1);
cell1.setCellValue(j+1);
cell1 = row.createCell(2);
cell1.setCellValue(j+2);
}
for (int i = 0; i < headers.length; i++) {
sheet.autoSizeColumn(i);
}
ByteArrayOutputStream os = new ByteArrayOutputStream(1000);
wb.write(os);
wb.close();
InputStreamSource iss = new ByteArrayResource(os.toByteArray());
os.close();
sendAttachmentsMail("收件人邮箱","抄送",
"主题",
"邮件内容",
iss, "excel名");
}
public boolean sendAttachmentsMail(String to,String cc, String subject, String content, InputStreamSource file, String fileName) throws MessagingException {
MimeMessage message = javaMailSender.createMimeMessage();
MimeMessageHelper smm = new MimeMessageHelper(message, true);
javaMailSender.setUsername("邮箱");
javaMailSender.setPassword("密码"));
//发件人
smm.setFrom(javaMailSender.getUsername());
//收件人
smm.setTo(to);
//抄送
if (!Objects.isNull(cc)) {
smm.setCc(cc);
}
//主题
smm.setSubject(subject);
//内容
smm.setText(content);
smm.addAttachment(fileName,file);
try {
javaMailSender.send(message);
return true;
} catch (MailException e) {
logger.error("邮件发送错误:{}", e);
}
return false;
}
}