邮件集成
需要的maven依赖
<!-- 邮件-->
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.7</version>
</dependency>
配置文件配置
- 基本参数设置
email.host=smtp.qq.com
email.protocol=smtp
email.username='发件人的邮箱号'
email.password='发件人的授权码'
-
授权码的获取
- 登陆QQ邮箱官网
- 开启服务(设置-账号)
- 点击生成授权码即可
-
xml中的配置信息
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.1.xsd">
<!-- 支持异步方法执行 -->
<task:executor id="myexecutor" pool-size="10" />
<bean id="emailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<!--邮件服务器-->
<property name="host" value="${email.host}"/>
<property name="protocol" value="${email.protocol}"/>
<!--邮箱号码-->
<property name="username" value="${email.username}"/>
<!--邮箱授权码-->
<property name="password" value="${email.password}"/>
<property name="defaultEncoding" value="UTF-8"/>
<property name="javaMailProperties">
<props>
<prop key="mail.smtp.auth">true</prop>
<prop key="mail.smtp.timeout">25000</prop>
</props>
</property>
</bean>
</beans>
测试及使用
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class EmailTest {
//注入邮件对象
@Autowired
JavaMailSenderImpl emailSender;
//设置发送人账号
@Value("${email.username}")
private String username;
//简单邮件
@Test
public void testEmail() throws Exception{
//得到信息对象
SimpleMailMessage smm = new SimpleMailMessage();
//发件人
smm.setFrom(username);
//收件人
smm.setTo("");
//发送标题
smm.setSubject("恭喜你获得大奖");
//发送信息
smm.setText("中了全世界");
emailSender.send(smm);
}
/*html邮件*/
@Test
public void testHtml() throws Exception{
//html信息
String html="<h1><font color='red'>恭喜你中大奖了</font></h1>";
MimeMessage mm = emailSender.createMimeMessage();
MimeMessageHelper mmh = new MimeMessageHelper(mm, true);
//发件人
mmh.setFrom(username);
//收件人
mmh.setTo("");
//发送标题
mmh.setSubject("恭喜你再中大奖");
//发送内容
mmh.setText(html, true);
emailSender.send(mm);
}
}