邮箱

  • 来源:新网
  • 更新日期:2018-03-14

摘要:package com.nine.util; import javax.imageio.ImageIO; import javax.servlet.http.HttpServletRequest; import com.nine.util.EmailThread; import com.google.zxing.*; import com.google.zxing.client.j2

package com.nine.util;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;

import com.nine.util.EmailThread;
import com.google.zxing.*;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import sun.misc.BASE64Encoder;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
import java.util.UUID;

import static com.google.zxing.client.j2se.MatrixToImageWriter.toBufferedImage;
import static com.google.zxing.client.j2se.MatrixToImageWriter.writeToFile;

public class TwoDimensionCode
{
public static class QRCodeTest {

/**
* @throws WriterException
* @throws IOException
*/
public void testEncodeToEmail(String content, int width, int height, String name, String format, String title, String address) throws WriterException, IOException {
String filePath = "D://";
String fileName = name + ".png";

Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);// 生成矩阵
Path path = FileSystems.getDefault().getPath(filePath, fileName);
MatrixToImageWriter.writeToPath(bitMatrix, "png", path);// 输出图像

Thread thread = new Thread(new EmailThread(content, title, address, filePath + fileName, fileName));
thread.run();
}
<<<<<<< HEAD
=======

public String returnQRCodePath(String content, int width, int height, String format, HttpServletRequest request) throws Exception{
String filePath = request.getSession().getServletContext().getRealPath("")+"/resources/img/";
String uuid= UUID.randomUUID().toString().replaceAll("-","");
String fileName = uuid + ".png";

Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);// 生成矩阵
Path path = FileSystems.getDefault().getPath(filePath, fileName);
MatrixToImageWriter.writeToPath(bitMatrix, "png", path);// 输出图像

String QRCodePath="/resources/img/"+fileName;
return QRCodePath;
}

>>>>>>> 9bfabb81561d39881f23480cbaa604741bf9f87f
/**
* 生成图像
*
* @throws WriterException
* @throws IOException
*/
public static BitMatrix testEncode(String filePath,String content ) {

int width = 200; // 图像宽度
int height = 200; // 图像高度
String format = "png";// 图像类型
BitMatrix bitMatrix =null;
try {
Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
// 生成矩阵
bitMatrix = new MultiFormatWriter().encode(content,
BarcodeFormat.QR_CODE, width, height, hints);
if(filePath!=null){
Path path = FileSystems.getDefault().getPath(filePath);
MatrixToImageWriter.writeToPath(bitMatrix, format, path);// 输出图像
System.out.println("输出成功.");
}
} catch (WriterException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return bitMatrix;
}



/**
* 解析图像
*/
//解析二维码
//fileName:被解析的二维码内容
public void readQRcode(String fileName) {
try {
MultiFormatReader formatReader = new MultiFormatReader();
File file = new File("d:/" + fileName + ".png");
BufferedImage image = ImageIO.read(file);//读取文件,识别成一个图片
BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(image)));
//二维码的参数
HashMap hints = new HashMap<>();
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
Result result = formatReader.decode(binaryBitmap, hints);

System.out.println("解析二维码的结果:" + result.toString());
System.out.println("二维码的格式:" + result.getBarcodeFormat());
System.out.println("二维码的内容:" + result.getText());
} catch (NotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}

public static String generalQRCode(String url) {
Hashtable hints = new Hashtable();
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
String binary = null;

try {
BitMatrix bitMatrix = new MultiFormatWriter().encode(
url, BarcodeFormat.QR_CODE, 200, 200, hints);

// 实现一: 输出图片到指定目录
// File outputFile = new File("d://1.jpg");
// MatrixToImageWriter.writeToFile(bitMatrix, "png", outputFile);

// 实现二:生成二维码图片并将图片转为二进制传递给前台
// 1、读取文件转换为字节数组
ByteArrayOutputStream out = new ByteArrayOutputStream();
BufferedImage image = toBufferedImage(bitMatrix);
////
ImageIO.write(image, "png", out);
byte[] bytes = out.toByteArray();

// 2、将字节数组转为二进制
BASE64Encoder encoder = new BASE64Encoder();
binary = encoder.encodeBuffer(bytes).trim();

} catch (Exception e) {
e.printStackTrace();
}

return binary;
}


/* public static void main(String[] arg0) throws IOException, WriterException {
QRCodeTest qrCodeTest = new QRCodeTest();
qrCodeTest.testEncodeToEmail("欧巴",300,300,"piao","png","接旨","2960882886@qq.com");
*//* qrCodeTest.testEncode("as",200,200,"bbb","png");
qrCodeTest.testEncode("",200,200,"deping","png");
qrCodeTest.readQRcode("ok");
*//*
String a = generalQRCode("D://c.png");


}*/

}

t01a36996002b45e9f0.jpg

 

 

package com.nine.util;

import java.util.Random;

public class RandomUtil {

//生成随机数字和字母
public static String getStringRandom() {
String val = "";
Random random = new Random();

//参数length,表示生成几位随机数
for(int i = 0; i < 4; i++) {

String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num";
//输出字母还是数字
if( "char".equalsIgnoreCase(charOrNum) ) {
//输出是大写字母还是小写字母
int temp = random.nextInt(2) % 2 == 0 ? 65 : 97;
val += (char)(random.nextInt(26) + temp);
} else if( "num".equalsIgnoreCase(charOrNum) ) {
val += String.valueOf(random.nextInt(10));
}
}
return val;
}
}

 

 

 

 

 

package com.nine.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.nine.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.nine.service.impl;

import com.nine.pojo.MyEmail;
import com.nine.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();
}
}
}

 

 

 

 

 

from=kojikazama@163.com
user=kojikazama
pwd=zhuhaojie9015
host=smpt.163.com

 

 

 

 

<html>
<head>
<title>管理员注册</title>
<script src="/resources/jquery/jquery-1.8.3.js"></script>
<script>

var flag1=false;
var flag2=false;
var flag3=false;

function checkEmail() {
var email=$("#eml").val();
$.ajax({
type: "get",
url: "/admin/checkEmail.action",
data: {email:email},
dataType: "json",
success: function (data) {
if(data.flag==0){
$("#s1").html("邮箱可用");
flag1=true;
}
else{
$("#s1").html("邮箱已注册");
flag1=false;
}
},
error: function () {
alert("系统繁忙,请稍后重试");
flag1=false;
}
});
}
function checkRealName() {
var realName=$("#rName").val();
realName=encodeURI(realName);
$.ajax({
type: "get",
url: "/admin/checkRealName.action",
data: {realName:realName},
dataType: "json",
success: function (data) {
if(data.flag==0){
$("#s2").html("用户姓名可用");
flag2=true;
}
else{
$("#s2").html("用户姓名已注册");
flag2=false;
}
},
error: function () {
alert("系统繁忙,请稍后重试");
flag2=false;
}
});
}

function sendCode() {
if (!flag1){
alert("邮箱不可用");
return;
}
var email=$("#eml").val();
$.ajax({
type: "get",
url: "/admin/sendCode.action",
data: {email:email},
dataType: "json",
success: function (data) {
alert("验证码已发送到你的邮箱");
$("#code2").val(data.code);
},
error: function () {
alert("系统繁忙,请稍后重试");
}
});
}

function checkCode() {
var code1=$("#code").val();
var code2=$("#code2").val();
if (code1==code2){
flag3=true;
}
else {
flag3=false;
}
}

function regAdmin() {
if(flag1&&flag2){
if (flag3){
alert("验证码正确");
}
else {
alert("验证码错误,请重新输入");
}
}
else {
alert("请检查表单");
return;
}
}
</script>
</head>
<style>
body {
display: flex;
align-items: center; /*定义body的元素垂直居中*/
justify-content: center; /*定义body的里的元素水平居中*/
background-size: 100% 100%;

}
.in{ width: 200px; margin-bottom: 28px;}
input{ border-radius: 15px 5px; height: 25px;}
</style>
<body>
<form action="/admin/regAdmin.action" enctype="multipart/form-data" method="post">
<table>
<tr><td>邮箱</td><td><input type="email" name="email" id="eml" onblur="checkEmail()" class="in"><span id="s1"></span></td></tr>
<tr><td>真实姓名</td><td><input name="realName" id="rName" onblur="checkRealName()" class="in"><span id="s2"></span></td></tr>
<tr><td>密码</td><td><input type="password" name="password" id="pwd" class="in"></td></tr>
<tr><td>头像</td><td><input type="file" name="file" class="in"></td></tr>
<tr><td>验证码</td><td><input id="code" onblur="checkCode()" class="in"><input type="hidden" id="code2" class="in"></td></tr>
<tr><td><input type="button" value="获取验证码" onclick="sendCode()"></td><td><input type="button" value="注册" onclick="regAdmin()"></td></tr>
</table>
</form>
</body>
</html>

 

 

 

 

 

 

 

 

 

 

//发送二维码验证
@RequestMapping(value = "sendCode",method = RequestMethod.GET)
@ResponseBody
public Map<String,Object> sendQRCode(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;

}