这次的邮件发送功能实现了,当用户登录时,向某个邮箱发送登录异常的邮件,还处在学习阶段,过程可供参考
发送邮箱的相关设置
需要打开邮箱的SMTP,POP3等服务器连接,设置授权码,之后的自动发送中可以通过设置邮箱名的授权码,来通过SMTP服务器发送邮件(打开方法为登录网页版邮箱,在设置中查找相关的选项开启)
发送邮箱前的初始化
在SenMails类中首先实现一个Bean初始化后的操作,即afterPropertiesSet中的内容
@Service
public class SendMails implements InitializingBean {
private JavaMailSenderImpl mailSender;
private static final Logger logger= LoggerFactory.getLogger(SendMails.class) ;
private FreeMarkerConfigurer freeMarkerConfigurer=new FreeMarkerConfigurer();
//mailSender初始化
@Override
public void afterPropertiesSet() throws Exception {
mailSender=new JavaMailSenderImpl();
mailSender.setUsername("xxx@126.com");//设置发送邮箱名
mailSender.setPassword("****");//设置Password
mailSender.setHost("smtp.126.com");//设置邮箱SMTP服务器地址(可以在邮箱服务网站上找到)
mailSender.setPort(465);
//设置端口号 !!!这里不要按照邮箱网站提供的端口,一开始用126提供的25,报错,后来在StackOverflow上找解决方法,改成465就好使了
mailSender.setProtocol("smtps");//设置协议
mailSender.setDefaultEncoding("utf8");//设置默认编码方式
Properties javaMailProperties=new Properties();
javaMailProperties.put("mail.smtp.auth", "true");
javaMailProperties.put("mail.smtp.ssl.enable", "true");
javaMailProperties.put("mail.smtp.socketFactory.fallback", "true");
mailSender.setJavaMailProperties(javaMailProperties);
}
}
具体邮件发送功能实现
//to--发给谁 subject---标题 template---模板 model---模板中变量的替换
public boolean sendWithHTMLTemplate(String to, String subject, String template, Map<String,Object> model)
{
try
{
String nick = MimeUtility.encodeText("AskMe系统消息");
InternetAddress from = new InternetAddress(nick + "<lily_young@126.com>");//加了一个昵称的发件人
MimeMessage mimeMessage = mailSender.createMimeMessage();//创建邮件文本
MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage);
Configuration configuration=new Configuration();
freeMarkerConfigurer.setConfiguration(configuration);
Template tpl=freeMarkerConfigurer.getConfiguration().getTemplate(template);
String result = FreeMarkerTemplateUtils.processTemplateIntoString(tpl,model);
//设置邮件发送的模板,和传进去的相关参数model
mimeMessageHelper.setTo(to);
mimeMessageHelper.setFrom(from);
mimeMessageHelper.setSubject(subject);
mimeMessageHelper.setText(result, true);//第二个参数true说明text是html格式的
mailSender.send(mimeMessage);//发送
}
catch(Exception e)
{
logger.error("发送邮件失败"+e);
return false;
}
return true;
}
发邮件的Handler
@Component
public class LoginExceptionHandler implements EventHandler{
@Autowired
SendMails sendMails;
@Autowired
UserService userService;
@Override
public void doHandle(EventModel event) {
Map<String,Object> map=new HashMap<String,Object>();
map.put("username",userService.getuserbyid(event.getUserid()).getName());
sendMails.sendWithHTMLTemplate(event.getkeyvalue("mail"),"用户登录异常","/src/main/resources/templates/mails/LoginException.html",map);
}
@Override
public List<EventType> getSupportEventType() {
return Arrays.asList(EventType.LOGIN);
}
}
在登录页面的Controller向异步队列添加事件
eventProducer.fireEvent(new EventModel().setkeyvalue("mail","xx@xx.com").setUserid(userservice.getUserByName(username).getId()).setEventype(EventType.LOGIN));