public void sendMailByAttachment(){
try {
MimeMessage mailMessage = senderImpl.createMimeMessage();
// multipart模式 为true时发送附件 可以设置html格式
MimeMessageHelper messageHelper = new MimeMessageHelper(
mailMessage, true, "utf-8");
// 设置收件人,寄件人
String[] receive=new String[]{"test@163com"};
messageHelper.setTo(receive);
messageHelper.setFrom(MessageUtils.getMessage("org.ceair.fms.email"));
messageHelper.setSubject("资金日报表!");
// true 表示启动HTML格式的邮件
messageHelper
.setText(
"<html><head></head><body>你好:附件为今天的资金日报表,请查阅!谢谢!</body></html>",
true);
String files[]=new String[]{"D:/fms.log","D:/请假或加班.txt"};
for(String filepath:files){
FileSystemResource file = new FileSystemResource(new File(
filepath));
messageHelper.addAttachment(MimeUtility.encodeWord(file.getFilename()), file); //MimeUtility.encodeWord处理乱码
}
// 发送邮件
senderImpl.send(mailMessage);
logger.info("邮件发送成功..");
} catch (Exception e) {
e.printStackTrace();
logger.error("邮件发送失败",e);
}
try {
MimeMessage mailMessage = senderImpl.createMimeMessage();
// multipart模式 为true时发送附件 可以设置html格式
MimeMessageHelper messageHelper = new MimeMessageHelper(
mailMessage, true, "utf-8");
// 设置收件人,寄件人
String[] receive=new String[]{"test@163com"};
messageHelper.setTo(receive);
messageHelper.setFrom(MessageUtils.getMessage("org.ceair.fms.email"));
messageHelper.setSubject("资金日报表!");
// true 表示启动HTML格式的邮件
messageHelper
.setText(
"<html><head></head><body>你好:附件为今天的资金日报表,请查阅!谢谢!</body></html>",
true);
String files[]=new String[]{"D:/fms.log","D:/请假或加班.txt"};
for(String filepath:files){
FileSystemResource file = new FileSystemResource(new File(
filepath));
messageHelper.addAttachment(MimeUtility.encodeWord(file.getFilename()), file); //MimeUtility.encodeWord处理乱码
}
// 发送邮件
senderImpl.send(mailMessage);
logger.info("邮件发送成功..");
} catch (Exception e) {
e.printStackTrace();
logger.error("邮件发送失败",e);
}
}
邮件spring 配置:
<!-- 邮件发送 -->
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="javaMailProperties">
<props>
<prop key="mail.smtp.auth">true</prop>
</props>
</property>
<property name="host" value="smtp.163.com" />
<property name="username" value="test@163.com" />
<property name="password" value="password" />
</bean>