步骤一:
package com.bw.pojo;
public class MyEmail {
private static MyEmail email;
private String host = "smtp.163.com"; // 发送方邮箱host
private String from = "17600246280@163.com"; // 发送方邮箱
private String user = "17600246280"; // 发送方邮箱账号
private String pwd = "ovel1314.21"; // 发送方邮箱密码
public static MyEmail getEmail(){
if(email!=null){
return email;
}else{
email = new MyEmail();
return email;
}
}
public String getFrom() {
return from;
}
public String getUser() {
return user;
}
public String getPwd() {
return pwd;
}
public String getHost() {
return host;
}
}
步骤二:
package com.bw.service;
public interface ISendEmailService {
/**
* 写一个发送邮件的方法
* @param content
* @param title
* @param address
* @param affix
* @param affixName
*/
void send(String content, String title, String address, String affix, String affixName);
}
实现类:
package com.bw.service.Impl;
import com.bw.pojo.MyEmail;
import com.bw.service.ISendEmailService;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
public class SendEmailServiceImpl implements ISendEmailService {
@Override
public void send(String content, String title, String address, String affix, String affixName) {
MyEmail myEmail = MyEmail.getEmail();
String host = myEmail.getHost();
String user = myEmail.getUser();
String pwd = myEmail.getPwd();
String from = myEmail.getFrom();
Properties props = new Properties();
// 设置发送邮件的邮件服务器的属性(这里使用网易的smtp服务器) -->需要修改
props.put("mail.smtp.host", host);
// 需要经过授权,也就是有户名和密码的校验,这样才能通过验证(一定要有这一条)
props.put("mail.smtp.auth", "true");
// 用刚刚设置好的props对象构建一个session
Session session = Session.getDefaultInstance(props);
// 有了这句便可以在发送邮件的过程中在console处显示过程信息,供调试使
// 用(你可以在控制台(console)上看到发送邮件的过程)
session.setDebug(true);
// 用session为参数定义消息对象
MimeMessage message = new MimeMessage(session);
try {
// 加载发件人地址 -->需要修改
message.setFrom(new InternetAddress(from));
// 加载收件人地址 -->需要修改
message.addRecipients(Message.RecipientType.TO, address);
List<InternetAddress> list = new ArrayList();//不能使用string类型的类型,这样只能发送一个收件人
String []median=address.split(",");//对输入的多个邮件进行逗号分割
for(int i=0;i<median.length;i++){
list.add(new InternetAddress(median[i]));
}
InternetAddress[] addresses =(InternetAddress[])list.toArray(new InternetAddress[list.size()]);
message.addRecipients(Message.RecipientType.TO, addresses);
// 加载标题 --->也需要修改
message.setSubject(title);
// 向multipart对象中添加邮件的各个部分内容,包括文本内容和附件
Multipart multipart = new MimeMultipart();
// 设置邮件的文本内容
BodyPart contentPart = new MimeBodyPart();
//需要修改的地方 写的内容
contentPart.setText(content);
multipart.addBodyPart(contentPart);
// 添加附件
if(affix != null && !"".equals(affix))
{
BodyPart messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(affix);
// 添加附件的内容
messageBodyPart.setDataHandler(new DataHandler(source));
// 添加附件的标题
// 这里很重要,通过下面的Base64编码的转换可以保证你的中文附件标题名在发送时不会变成乱码
sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();
messageBodyPart.setFileName("=?GBK?B?"+ enc.encode(affixName.getBytes()) + "?=");
multipart.addBodyPart(messageBodyPart);
}
// 将multipart对象放到message中
message.setContent(multipart);
// 保存邮件
message.saveChanges();
// 发送邮件
Transport transport = session.getTransport("smtp");
// 连接服务器的邮箱
transport.connect(host, user, pwd);
// 把邮件发送出去
transport.sendMessage(message, message.getAllRecipients());
transport.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
步骤三:
package com.bw.controller;
import com.bw.pojo.User;
import com.bw.service.IUserService;
import com.bw.util.FileUtil;
import com.bw.util.RandomUtil;
import com.bw.util.TwoDimensionCode;
import com.google.zxing.WriterException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Controller
@RequestMapping("/user")
public class UserController {
@Resource
private IUserService iUserService;
//查询所有
@RequestMapping("selUser")
public ModelAndView selUser(ModelAndView modelAndView) throws Exception{
List<User> userList= iUserService.selUser();
modelAndView.addObject("userList",userList);
modelAndView.setViewName("show");
return modelAndView;
}
//模糊查询
@RequestMapping("fuzzyUser")
public ModelAndView fuzzyUser(ModelAndView modelAndView,String name){
List<User> fuzzyUser= iUserService.fuzzyUser(name);
modelAndView.addObject("fuzzyUser",fuzzyUser);
modelAndView.setViewName("show");
return modelAndView;
}
//注册
@RequestMapping("registerUser")
public ModelAndView registerUser(@RequestParam(value = "file",required = false)MultipartFile file, HttpServletRequest request, ModelAndView modelAndView, User user)throws Exception{
if (!file.isEmpty()){
String headPhoto= FileUtil.uploadFile(file,request);
user.setName(headPhoto);
}else {
user.setName(null);
}
iUserService.registerUser(user);
modelAndView.setViewName("redirect:/user/selUser.action");
return modelAndView;
}
//发送二维码验证
@RequestMapping(value = "sendCode",method = RequestMethod.GET)
@ResponseBody
public Map<String,Object> sendCode(String email) throws IOException, WriterException {
String title="XXX资讯后台管理系统";
String code= RandomUtil.getStringRandom();
String content="欢迎注册本平台,你的验证码是:"+code;
TwoDimensionCode.QRCodeTest qrCodeTest = new TwoDimensionCode.QRCodeTest();
qrCodeTest.testEncodeToEmail(content,300,300,"piao","png",title,email);
Map<String,Object> map=new HashMap<>();
map.put("checkCode",code);
return map;
}
//检查邮箱是否重复
@RequestMapping(value = "/checkEmail",method = RequestMethod.GET)
@ResponseBody
public Map<String,Object> checkEmail(String email){
Map<String,Object> map=new HashMap<>();
map.put("flag","邮箱没有重复!");
return map;
}
//批量删除
@RequestMapping("batchUser")
public ModelAndView batchUser(ModelAndView modelAndView,String ids){
iUserService.batchUser(ids);
modelAndView.setViewName("show");
return modelAndView;
}
}
步骤四:
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2017/9/21/021
Time: 15:31
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" isELIgnored="false" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path;
%>
<html>
<head>
<title>Title</title>
<script src="/resources/jquery/jquery-1.8.3.js"></script>
<script>
function sendCode() {
var email=$("#eml").val();
$.ajax({
type: "get",
url: "/user/sendCode.action",
data: {email:email},
dataType: "json",
success: function (data) {
alert("验证码已发送到你的邮箱");
$("#code2").val(data.code);
},
error: function () {
alert("系统繁忙,请稍后重试");
}
});
}
</script>
</head>
<body>
<h2>首页</h2>
<form action="/user/registerUser.action" enctype="multipart/form-data" method="post">
上传图片:<input type="file" name="file" /><br>
用户邮箱:<input type="text" name="email" id="eml"/><br>
用户Miami:<input type="text" name="password"/><br>
用户余额:<input type="text" name="balance" /><br>
<input type="button" value="获取验证码" οnclick="sendCode()"/>
<input type="submit" value="注册" />
</form>
</body>
</html>