邮箱验证工具类

import com.itszt.jzzj.domain.user.User;
import java.io.*;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
/**
 * 邮箱链接验证
 * 基于网易云信,详情请参考网易云信官方API
 */
public class SendJMail {
	public static boolean sendMail(String email, User user) {
		String from = "13522624136@163.com"; // 邮件发送人的邮件地址
		String to = email.trim(); 										// 邮件接收人的邮件地址
		final String username = "13522624136";  //发件人的邮件帐户
		final String password = "shijian321";   					//发件人的邮件密码
		//定义Properties对象,设置环境信息
		Properties props = System.getProperties();
		//设置邮件服务器的地址
		props.setProperty("mail.smtp.host", "smtp.163.com"); // 指定的smtp服务器
		props.setProperty("mail.smtp.auth", "true");
		props.setProperty("mail.transport.protocol", "smtp");//设置发送邮件使用的协议
		//创建Session对象,session对象表示整个邮件的环境信息
		Session session = Session.getInstance(props);
		//设置输出调试信息
		session.setDebug(true);
		try {
			//Message的实例对象表示一封电子邮件
			MimeMessage message = new MimeMessage(session);
			//设置发件人的地址
			message.setFrom(new InternetAddress(from));
			//设置主题
			message.setSubject("尊敬的:"+user.getAccount()+"您的兼职之家激活邮件");
			//设置邮件的文本内容
//			message.setText("<h1>我是大黄!!</h1>");
			message.setContent(genEmilMsg(user),"text/html;charset=utf-8");
			//从session的环境中获取发送邮件的对象
			Transport transport=session.getTransport();
			//连接邮件服务器
			transport.connect("smtp.163.com",25, username, password);
			//设置收件人地址,并发送消息
			transport.sendMessage(message,new Address[]{new InternetAddress(to)});
			transport.close();
			return true;
		} catch (MessagingException e) {
			e.printStackTrace();
			sendMail(email,user);
			return false;
		}
	}
	private static String genEmilMsg(User user){
		try {
			BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(new FileInputStream(UtilGetRealPath.getRealPath("/激活页面.html")),"UTF-8"));
			StringBuilder stringBuilder=new StringBuilder();
			String temp=null;
			while ((temp=bufferedReader.readLine())!=null){
				temp=temp.replace("dahuang",user.getAccount());
				temp=temp.replace("http://www.baidu.com","http://localhost/ActiveServlet?userID="+user.getUserid()+"&useraccount="+user.getAccount());
                stringBuilder.append(temp);
            }
            return stringBuilder.toString();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "hello";
	}
//	public static void main(String[] args) throws IOException {
//		sendMail("zhanzhitang111@163.com",stringBuilder.toString());
////		sendMail("zhanzhitang111@163.com","<div>你好2</div>");
//	}
}  
posted @ 2018-03-22 18:59  奔跑在梦想的道路上  阅读(387)  评论(0编辑  收藏  举报