SSM整合框架实现发送邮件功能
1.导入发送邮件的依赖
<!-- 发送邮件jar包--><!--spring支持--><dependency><groupId>org.springframework</groupId><artifactId>spring-context-support</artifactId><version>5.0.0.RELEASE</version></dependency><!--邮件发送--><dependency><groupId>com.sun.mail</groupId><artifactId>javax.mail</artifactId><version>1.6.1</version></dependency>
2.发送邮件的账号开启POP3/SMTP/IMAP/SMIP服务
3.spring-mybatis.xml配置文件中添加发送邮件所需的配置信息
<!--邮件配置--><context:property-placeholder location="classpath:email.properties" ignore-unresolvable="true"/><!--配置邮件接口--><bean id="javaMailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl"><property name="host" value="${mail.smtp.host}"/><property name="username" value="${mail.smtp.username}"/><property name="password" value="${mail.smtp.password}"/><property name="defaultEncoding" value="${mail.smtp.defaultEncoding}"/><property name="javaMailProperties"><props><prop key="mail.smtp.auth">${mail.smtp.auth}</prop><prop key="mail.smtp.timeout">${mail.smtp.timeout}</prop></props></property></bean>
4.创建email.properties 接上配置邮件接口
#服务器主机名 smtp.xx.com
mail.smtp.host=smtp.qq.com
mail.smtp.username=开启服务的邮箱号@qq.com
#密码/客户端授权码
mail.smtp.password=开启服务的邮箱号的密钥
#编码字符
mail.smtp.defaultEncoding=utf-8
#是否进行用户名密码校验
mail.smtp.auth=true
#设置超时时间
mail.smtp.timeout=20000
5.在控制层测试
package com.mvo.controller;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.io.IOException;
import java.util.Properties;
@Controllerpublic class SendMailController {@Autowiredprivate JavaMailSender javaMailSender;@RequestMapping("sendMailTest")public Object sendMailTest(){MimeMessage mMessage=javaMailSender.createMimeMessage();MimeMessageHelper mMessageHelper;Properties prop = new Properties();String from;try {prop.load(this.getClass().getResourceAsStream("/email.properties"));from = prop.get("mail.smtp.username")+"";mMessageHelper=new MimeMessageHelper(mMessage,true);mMessageHelper.setFrom(from);mMessageHelper.setTo("收件人邮箱号@qq.com");mMessageHelper.setSubject("ssm框架测试邮件发送");mMessageHelper.setText("<p>这是使用spring,springmvc,mybatis整合框架的邮件功能发送的一封邮件,测试</p>",true);File file=new File("C:\\Users\\lcl\\Pictures\\Saved Pictures\\blog.csdn.net_Mr__Viking_article_details_81090046.png");FileSystemResource resource=new FileSystemResource(file);javaMailSender.send(mMessage);} catch (MessagingException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}return "发送成功";}
}
启动项目 --> 输入地址测试
6.效果图