1. Spring整合JavaMail
1.1. 添加依赖
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>5.3.2</version> </dependency> <dependency> <groupId>javax.activation</groupId> <artifactId>activation</artifactId> <version>1.1.1</version> </dependency> <dependency> <groupId>com.sun.mail</groupId> <artifactId>javax.mail</artifactId> <version>1.6.2</version> </dependency>
1.2. spring配置
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl"> <property name="host" value="smtp.qq.com" /> <property name="username" value="自己的邮箱1025205118@qq.com" /> <property name="password" value="自己的授权码" /> <property name="javaMailProperties"> <props> <!-- 授权认证,防止乱发邮件 --> <prop key="mail.smtp.auth">true</prop> <!-- SMTP加密方式,连接到一个TLS保护连接 --> <prop key="mail.smtp.starttls.enable">true</prop> <!-- 设置邮件发送超时时间 --> <prop key="mail.smtp.timeout">25000</prop><!-- <prop key="mail.smtp.ssl.enable">true</prop>--> </props> </property> </bean> <context:component-scan base-package="com.wanmait.mavendemo.mail"/>
1.3. 使用SimpleMailMessage发送邮件
JavaMail的集成API是在spring-context-support的 org.springframework.mail 包中,需要 JavaMail 的类库支持。MailSender 是发送电子邮件的核心接口,spring提供了邮件的简单封装类 SimpleMailMessage。
1.3.1. 发送普通邮件
@Component public class MailUtil { @Resource private MailSender mailSender; public void sendMsg() throws ParseException { SimpleMailMessage smm = new SimpleMailMessage(); // 发送 smm.setFrom("1025205118@qq.com"); // 接收 smm.setTo("wangrf@qingsoft.net"); // 主题 smm.setSubject("hello world" + System.currentTimeMillis()); //设置抄送 smm.setCc("sunm@qingsoft.net"); //设置密送 //smm.setBcc("sunm@qingsoft.net"); // 内容 smm.setText("hello,how are you !"); //设置邮件显示的发送时间 不设置默认当前系统时间,设置到当前时间之前不会发送 //smm.setSentDate(new Date()); mailSender.send(smm); } } @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:spring.xml") public class MailTest { @Resource private MailUtil mailUtil; @Test public void testSendMail() throws ParseException { mailUtil.sendMsg(); } }
1.3.2. 发送统一标题和内容邮件
在spring配置文件中再加上如下配置:
<bean id="templateMessage" class="org.springframework.mail.SimpleMailMessage"> <property name="from" value="1025205118@qq.com"/> <property name="subject" value="统一标题"/> <property name="text" value="统一内容"/> </bean>
发送邮件
@Resource private SimpleMailMessage simpleMailMessage; public void sendMsgWithTemplate() throws ParseException { SimpleMailMessage smm = new SimpleMailMessage(simpleMailMessage); smm.setTo("wangrf@qingsoft.net"); mailSender.send(smm); }
1.4. 使用MimeMessage发送邮件
spring 框架的邮件支持也附带了标准 JavaMail 实现,JavaMailSender 类可以使用 JavaMail 的 MimeMessage类来发送邮件。
1.4.1. 使用JavaMailSender 和 MimeMessagePreparator
@Resource private JavaMailSender javaMailSender; public void sendMimeMsg() { String[] tos = {"62999860@qq.com","wangrf@qingsoft.net"}; MimeMessagePreparator preparator = (MimeMessage mimeMessage) ->{ Arrays.asList(tos).stream().forEach(to->{ try { mimeMessage.setRecipient(Message.RecipientType.TO,new InternetAddress(to)); } catch (MessagingException e) { e.printStackTrace(); } }); mimeMessage.setFrom("1025205118@qq.com"); mimeMessage.setSubject("spring邮件"); String content="hello 你好"; mimeMessage.setContent(content, "text/html;charset=UTF-8"); }; javaMailSender.send(preparator); }
1.4.2. 使用JavaMailSender创建MimeMessage
public void sendMimeMsg2() throws MessagingException { MimeMessage mimeMessage = javaMailSender.createMimeMessage(); mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress("wangrf@qingsoft.net")); mimeMessage.setFrom("1025205118@qq.com"); mimeMessage.setSubject("spring邮件111"); String content = "hello 你好"; mimeMessage.setContent(content, "text/html;charset=UTF-8"); javaMailSender.send(mimeMessage); }
1.4.3. 借助MimeMessageHelper处理邮件
public void sendMimeMsg3() throws MessagingException { MimeMessage mimeMessage = javaMailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(mimeMessage); helper.setFrom("1025205118@qq.com"); helper.setTo("wangrf@qingsoft.net"); helper.setCc("62999860@qq.com"); helper.setSubject("hello"); helper.setText("hello,how are you ! "); javaMailSender.send(mimeMessage); }
1.4.4. 使用MimeMessageHelper 发送带附件和内联资源的邮件
public void sendMimeMsg4() throws MessagingException { MimeMessage mimeMessage = javaMailSender.createMimeMessage(); //true表示创建多部分组成带附件的邮件 MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,"UTF-8"); helper.setFrom("1025205118@qq.com"); helper.setTo("wangrf@qingsoft.net"); helper.setCc("62999860@qq.com"); helper.setSubject("hello"); //true表示邮件内容为HTML helper.setText("<html><body><h1>邮件内容</h1><p>Hello,how are you !</p><img src=\"cid:inlineImg\"/></body></html>",true); //添加附件 FileSystemResource resource = new FileSystemResource(new File("d:/log.txt")); helper.addAttachment("1.txt",resource); //添加内联资源,设置图片 FileSystemResource imageResource = new FileSystemResource(new File("d:/images/1.jpg")); helper.addInline("inlineImg",imageResource); javaMailSender.send(mimeMessage); }
收件箱收到的邮件如下:
1.5. 使用模板创建邮件
一般使用代码创建邮件不会是简单的纯文本邮件,在使用Java代码创建基于HTML的电子邮件内容非常繁琐且容易出错,而且更改电子邮件内容的显示结构需要编写Java代码,重新编译,重新部署
使用模板可以解决这些问题,使用模板库(例如FreeMarker、Velocity、Thymeleaf)来定义电子邮件内容的显示结构。从 Spring 4.3 之后,Velocity支持已被弃用。
下面使用 FreeMaker 模板发送邮件。
1.5.1. 添加依赖
<dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>2.3.30</version> </dependency>
1.5.2. 添加配置
<bean id="freeMarkerConfiguration" class="org.springframework.ui.freemarker.FreeMarkerConfigurationFactoryBean"> <property name="templateLoaderPath" value="classpath:template/ftl/" /> <property name="freemarkerSettings"> <props> <!--模板更新延时--> <prop key="template_update_delay">1800</prop> <prop key="default_encoding">UTF-8</prop> <prop key="locale">zh_CN</prop> </props> </property> </bean>
1.5.3. 邮件模板文件
放在resources下面的template/ftl文件夹下:
<html> <body> <h3>${article.title}</h3> <p>${article.info}</p> <span>From wanmait.com</span> </body> </html>
1.5.4. 邮件发送类
@Component public class TemplateMailManager { @Resource private JavaMailSender mailSender; @Resource private Configuration freeMarkerConfiguration; public void sendMail(Article article,String... to) { MimeMessage message = mailSender.createMimeMessage(); try { // 使用 true 表示要创建一个有多部分的邮件 MimeMessageHelper helper = new MimeMessageHelper(message, true, "utf-8"); helper.setFrom("1025205118@qq.com"); helper.setTo(to); helper.setSubject("Freemarker模板邮件"); //获取模板 Map<String, Object> model = new HashMap<String, Object>(); model.put("article", article); String text = geFreeMarkerTemplateContent(model); // 使用 true 表示邮件内容为 HTML helper.setText(text, true); this.mailSender.send(message); } catch (MailException | MessagingException ex) { System.err.println(ex.getMessage()); } } //获得模板内容 private String geFreeMarkerTemplateContent(Map<String, Object> model) { String content = null; try { content = FreeMarkerTemplateUtils.processTemplateIntoString(freeMarkerConfiguration.getTemplate("article.ftl"), model); } catch (Exception e) { System.err.println(e.getMessage()); } return content; } }
1.5.5. 测试发送
@Resource private TemplateMailManager mailManager; @RequestMapping("sendMail") @ResponseBody public String sendMail() { Article article = new Article(); article.setTitle("万码云课已经上线,哈哈"); article.setInfo("JavaEE高端框架,大数据,云计算应有尽有,欢迎观看!"); mailManager.sendMail(article,"wangrf@qingsoft.net","62999860@qq.com"); return "success"; }
0条评论
点击登录参与评论