刚开始学习spring-boot,所以就从demo入手,整好需要发送邮件功能,所以就以发送邮件为目的来学习使用spring-boot.
一、POM文件
在pom.xml中增加以下依赖
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.2.4.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
</dependencies>
其它相关依赖包根据自己需要添加
二、具体代码实现
这里以163邮箱为例,因为一直都是163的忠实使用者。如果使用qq邮箱,需要注意授权验证,不过可以放心的是,如果忘记了,给出的异常会很人性的给出url,点击查看即可看到解决办法。
首先创建配置文件,具体位置为
以下是文件的内容
###mail setting###
# 设置邮箱主机及端口
email.host=smtp.163.com
email.port=25
# 设置用户名
email.from=xxxxxxx@163.com
# 设置密码
email.from.password=xxxxxxx
# 设置是否需要认证,如果为true,那么用户名和密码就必须的,
# 如果设置false,可以不设置用户名和密码,当然也得看你的对接的平台是否支持无密码进行访问的。
email.smtp.auth=false
--------------------------------------------------------------------------------------------------- 以下是代码正题 ---------------------------------------------------------------------------------------------------
MailPropKey,是与配置文件对应的常量,便于统一,避免各处直接写会粗心写错
package com.mail;
public interface MailPropKey {
String EMAIL_FROM = "email.from";
String EMAIL_FROM_PASSWORD = "email.from.password";
String EMAIL_HOST = "email.host";
String EMAIL_PORT = "email.port";
String EMAIL_SMTP_AUTH = "email.smtp.auth";
}
package com.mail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
import java.util.Properties;
@Configuration
public class MailConfig {
@Autowired
private Environment env;
@Bean(name = "JavaMailSender")
public JavaMailSender getSender()
{
JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
javaMailSender.setUsername(env.getProperty(MailPropKey.EMAIL_FROM));
javaMailSender.setPassword(env.getProperty(MailPropKey.EMAIL_FROM_PASSWORD));
javaMailSender.setHost(env.getProperty(MailPropKey.EMAIL_HOST));
javaMailSender.setPort(Integer.parseInt(env.getProperty(MailPropKey.EMAIL_PORT)));
javaMailSender.setDefaultEncoding("UTF-8");
Properties props = new Properties();
props.setProperty("mail.smtp.host", env.getProperty(MailPropKey.EMAIL_HOST));
props.setProperty("mail.smtp.auth", env.getProperty(MailPropKey.EMAIL_SMTP_AUTH));
javax.mail.Session session = javax.mail.Session.getDefaultInstance(props,new Authenticator(){
@Override
protected PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication(env.getProperty(MailPropKey.EMAIL_FROM), env.getProperty(MailPropKey.EMAIL_FROM_PASSWORD));
}
});
javaMailSender.setSession(session);
return javaMailSender;
}
}
MailHelper,这是对邮件发送的封装,这里知识发送简单的邮件用来测试,复杂的需要引入其它的模版依赖
package com.mail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
@Service
public class MailHelper {
@Autowired
private Environment env;
@Autowired
private JavaMailSender javaMailSender;
public void sendSimpleEmail()
{
SimpleMailMessage msg = new SimpleMailMessage();
msg.setFrom(env.getProperty(MailPropKey.EMAIL_FROM));
msg.setTo("xxxx@xxxxxxxx.com");
msg.setSubject("Test spring boot mail.");
msg.setText("This is test message.");
javaMailSender.send(msg);
}
}
做了一个简单的controller用来测试,没有使用Junit的方式
package com.controller;
import com.mail.MailHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
@RestController
public class MailController {
private static final Logger LOGGER = LoggerFactory.getLogger(MailController.class);
@Resource
private MailHelper mailHelper;
@RequestMapping("/mail")
public String mail(HttpServletRequest request)
{
LOGGER.info("start send mail...");
mailHelper.sendSimpleEmail();
LOGGER.info("end send mail...");
return "Send mail ok.";
}
}
启动类,用来启动spring-boot服务
package com;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration//配置控制
@EnableAutoConfiguration//启用自动配置
@ComponentScan//组件扫描
public class Bootstrap {
private static final Logger LOGGER = LoggerFactory
.getLogger(Bootstrap.class);
public static void main(String[] args) throws Exception {
SpringApplication.run(Bootstrap.class, args);
LOGGER.info("Server running...");
}
}
三、测试
成功启动后,在浏览器输入http://localhost:8080/mail,回车
页面上会显示如下内容
Send mail ok.
而我也如愿收到了邮件