邮件带附件发送
依赖
1 2 3 4 5 6 7 8 9 10
| <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来进行发送附件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
| JavaMailSenderImpl sender = new JavaMailSenderImpl(); sender.setHost("smtp.exmail.qq.com"); sender.setPort(587); 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"); helper.setText(textBody, true); helper.addAttachment(file.getName(),file); sender.send(mail); }catch(Exception e) { }
|