文章目录
邮件带附件发送
依赖
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-email</artifactId>
<version>1.5</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>4.3.29.RELEASE</version>
</dependency>
有时候发送邮件需要带有附件,可以使用MimeMessageHelper来进行发送附件
JavaMailSenderImpl sender = new JavaMailSenderImpl();
sender.setHost("smtp.exmail.qq.com");
sender.setPort(587); // 默认就是25
sender.setUsername("username");
sender.setPassword("password");
sender.setDefaultEncoding("UTF-8");
// 配置文件对象
Properties props = new Properties();
props.put("mail.smtp.auth", "true"); // 是否进行验证
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtps.ssl.checkserveridentity", "true");
props.put("mail.smtps.ssl.trust", "*");
Session session = Session.getInstance(props);
sender.setSession(session);
MimeMessage mail = sender.createMimeMessage();
MimeMessageHelper helper;
try {
// 开启发送文件
helper = new MimeMessageHelper(mail,true);
} catch (MessagingException e) {
return false;
}
try {
helper.setTo(to); // 发送给谁
helper.setCc(cc); // 抄送
helper.setSubject(title); // 标题
helper.setFrom("username"); // 来自
// 邮件内容,第二个参数指定发送的是HTML格式
helper.setText(textBody, true);
// 发送附件
helper.addAttachment(file.getName(),file);
sender.send(mail); // 发送
}catch(Exception e) {
}
参考文献