必威体育Betway必威体育官网
当前位置:首页 > IT技术

javaMail实现邮件发送

时间:2019-11-03 16:14:33来源:IT技术作者:seo实验室小编阅读:90次「手机版」
 

www.263.net

平常我们在做登陆注册的时候需要需要对邮箱进行验证,向邮箱发送验证信息。下面是我在做注册的时候向邮箱发送验证码代码

邮箱校验正则

邮箱匹配规则:boolean mflag = mail.matches("^\\s*\\w+(?:\\.{0,1}[\\w-]+)*@[a-zA-Z0-9]+(?:[-.][a-zA-Z0-9]+)*\\.[a-zA-Z]+\\s*$");

邮箱发送入口

if(!mflag){
	result.setCode("-1");
	result.setmessage("邮箱格式验证不正确");
}else {
	//获取随机的六位数字 用于发送验证码
	String identifyingCode = SendEmailUtils.generatePassword();
	
	//拼装邮件内容   发送邮件的具体内容
	String emailcontent = getEmailContent4RegEmail(identifyingCode);
	
        //将验证码放入缓存服务器memcache 
	MemcacheUtil.set(mail, 30, identifyingCode);
	
	//邮件服务器地址  从配置文件中读取邮件服务器地址
	String mailHost = SendEmailUtils.getPropValue("mail.smtp.host");
	
	//发送人邮箱     <span style="font-family: Arial, helvetica, sans-serif;">从配置文件中读取发送人邮箱</span>
	String mailEmail = SendEmailUtils.getPropValue("mail.smtp.email");
	
	//邮箱用户名     从配置文件中读取发送人邮箱用户名
	String mailUser = SendEmailUtils.getPropValue("mail.smtp.user");
	
	//邮箱密码      从配置文件中读取发送人邮箱密码
	String mailPassword = SendEmailUtils.getPropValue("mail.smtp.password");
	
	//邮件主题
	String title = "****邮箱注册";
	
	//发送邮箱  参数包括  发送目的地邮箱    发送人邮箱   邮件主题  邮件内容  邮件服务器  发送人邮箱用户名  发送人邮箱密码  是否是html格式
	new SendEmailUtils().send(mail, mailEmail, title, emailContent,
			mailHost, mailUser, mailPassword, true);
	
	Map<String, String> reMap = new HashMap<String, String>();
	
	reMap.put("sendCode", identifyingCode);
	
	result.setData(reMap);
	result.setCode("1");
	result.setMessage("发送成功");
}

拼装邮件内容(html格式的)
private String getEmailContent4RegEmail(String identifyingCode) {
		stringbuilder emailContent = new StringBuilder()
		.APPend("您在***进行邮箱注册操作的验证码为:<span style=\"color: #F3750F;font-weight: bold;font-size: larger;font-family: cursive;\">")
		.append(identifyingCode).append("</span><br/>")
		.append("此验证码只能使用一次,验证成功自动失效;<br/>")
		.append("<p style=\"font-size: small;color: gray;\">")
		.append("(请在10分钟内完成验证,10分钟后验证码失效,您需要重新进行验证。感谢您对***的支持。)<br/>")
		.append("如果您错误的收到了本电子邮件,请您忽略上述内容<br/>").append("</p>");
		return emailContent.toString();
	}
发送邮件工具
import java.io.InputStream;
import java.util.Date;
import java.util.Properties;
import java.util.Random;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.apache.log4j.Logger;



public class SendEmailUtils {
	/** 邮件随机数 */
	public static Random random = new Random();
	//邮箱服务器
	public static String MAILHOST="";
	public static String MAILEMAIL="";
	public static String MAILUSER="";
	public static String MAILPASSWORD="";
	public static String MAILADDRESS="";
	
	private static Properties prop = null;
	static{
		String path = "/com/conf/mail.properties";
		
		InputStream in = SendEmailUtils.class.getResourceAsStream(path);
		if ( in != null ){
			prop = new Properties();
			try{
				prop.load(in);
				MAILHOST = (String) prop.get("mail.smtp.host");
				MAILEMAIL = (String) prop.get("mail.smtp.email");
				MAILUSER=(String)prop.get("mail.smtp.user");
				MAILPASSWORD=(String)prop.get("mail.smtp.password");
			} catch (Exception e){
				throw new runtimeexception(e);
			}
		}
	}
	public static String getPropValue(String key){
		String path = "/com/conf/mail.properties";
		String val = null;
		InputStream in = SendEmailUtils.class.getResourceAsStream(path);
		if ( in != null ){
			prop = new Properties();
			try{
				prop.load(in);
				val = prop.getProperty(key);
			} catch (Exception e){
				e.printstacktrace();
				System.out.println("=====================get property file ERROR!");
			}
		}
		return val;
	}
	
	
	private static Logger logger = Logger.getLogger(SendEmailUtils.class);
	//发送邮件相关
	/**
	 * 生成密码(6位随机数字)
	 * @return String
	 * @author HuKaiXuan 2014-5-17 上午11:16:18
	 */
	public static String generatePassword(){
		String number = "";
		for(int i = 0; i < 6; i ++) {
			number += random.nextint(10);
 		}
		return number;
	}
	
	public static void main(String[] args) {
		String propValue = new SendEmailUtils().getPropValue("mail.smtp.host");
		System.out.println(propValue);
		/*Random random = new Random();
		String password = random.nextInt() + "";
		StringBuffer content = new StringBuffer();
		content.append("您好!用户 Mr.Men ***** 在radio的密码为:" + password + "<br/>(该邮件为系统邮件,请勿回复,登录后请及时修改您的密码。)");

		String mailHost = "smtp.163.com";// pu.getValue("mail.send.host");
		String mailEmail = "***[email protected]";// pu.getValue("mail.send.email");
		String mailUser = "***2010";// pu.getValue("mail.send.user");
		String mailPassword = "***";// pu.getValue("mail.send.password");
		try {
			new SendEmailUtils().send("****@qq.com", mailEmail, "密码重置", content.toString(), mailHost, mailUser, mailPassword, false);
			System.out.println("Mail Send Success");
		} catch (AddressException e) {
			System.out.println("AddressException-------" + e.getMessage());
			e.printStackTrace();
		} catch (MessagingException e) {
			System.out.println("MessagingException-------" + e.getMessage());
			e.printStackTrace();
		}*/
	}
	
	/***************************************************************************
	 * 邮件发送,带用户名和密码验证,测试通过
	 * 
	 * @param to       发送目的地邮箱
	 * @param from     发送来源地邮箱   
	 * @param title    邮箱主题
	 * @param content  邮箱内容
	 * @param smtpServer 邮箱服务器
	 * @param user       邮箱有户名 
	 * @param password   邮箱密码
	 * @param ishtml     是否是Html
	 * @throws AddressException
	 * @throws MessagingException
	 */
	public void send(String to, String from, String title, String content,
			String smtpServer, String user, String password, boolean isHTML)
			throws AddressException, MessagingException {

		Properties props = new Properties();
		Authenticator auth = new MailAuthenticator(user, password);
		Session sendMailSession;
		Transport transport;
		props.put("mail.smtp.host", smtpServer);
		props.put("mail.smtp.auth", "true");
		sendMailSession = Session.getinstance(props, auth);
		Message newMessage = new MimeMessage(sendMailSession);
		newMessage.setFrom(new InternetAddress(from));
		newMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(
				to));
		newMessage.setsubject(title);
		newMessage.setSentDate(new Date());
		if (isHTML) {
			newMessage.setContent(content, "text/html;charset=UTF-8");
		} else {
			newMessage.setText(content);
		}
		transport = sendMailSession.getTransport("smtp");
		Transport.send(newMessage);
		transport.close();
		if (logger.isDebugEnabled()) {
			logger.debug("---------- Mail Send Success ----------");
		}
	}
	
	
}
class MailAuthenticator extends Authenticator {
	private String user;
	private String password;

	public MailAuthenticator() {

	}

	public MailAuthenticator(String user, String password) {
		this.user = user;
		this.password = password;
	}

	protected PasswordAuthentication getPasswordAuthentication() {
		return new PasswordAuthentication(user, password);
	}

	public String getMailServer(String email) {
		String mailUrl = "/";
		if (null != email) {
			mailUrl = email.toLowerCase();
			String email_array = email.substring(email.indexof("@"));
			if ("163.com".equals(email_array)) {// 163邮箱
				mailUrl = "mail.163.com";
			} else if ("vip.163.com".equals(email_array)) {// 163vip邮箱
				mailUrl = "vip.163.com";
			} else if ("sina.com".equals(email_array)) {// 新浪邮箱
				mailUrl = "mail.sina.com.cn";
			} else if ("sina.cn".equals(email_array)) {// 新浪邮箱
				mailUrl = "mail.sina.com.cn";
			} else if ("vip.sina.com".equals(email_array)) {// 新浪vip邮箱
				mailUrl = "vip.sina.com.cn";
			} else if ("2008.sina.com".equals(email_array)) {// 新浪2008邮箱
				mailUrl = "mail.2008.sina.com.cn";
			} else if ("sohu.com".equals(email_array)) {// 搜狐邮箱
				mailUrl = "mail.sohu.com";
			} else if ("vip.sohu.com".equals(email_array)) {// 搜狐vip邮箱
				mailUrl = "vip.sohu.com";
			} else if ("tom.com".equals(email_array)) {// Tom邮箱
				mailUrl = "mail.tom.com";
			} else if ("vip.sina.com".equals(email_array)) {// Tom vip 邮箱
				mailUrl = "vip.tom.com";
			} else if ("sogou.com".equals(email_array)) {// 搜狗邮箱
				mailUrl = "mail.sogou.com";
			} else if ("126.com".equals(email_array)) {// 126邮箱
				mailUrl = "www.126.com";
			} else if ("vip.126.com".equals(email_array)) {// 126 vip 邮箱
				mailUrl = "vip.126.com";
			} else if ("139.com".equals(email_array)) {// 139邮箱
				mailUrl = "mail.10086.cn";
			} else if ("gmail.com".equals(email_array)) {// gmail邮箱
				mailUrl = "www.gmail.com";
			} else if ("hotmail.com".equals(email_array)) {// 139邮箱
				mailUrl = "login.live.com";
			} else if ("189.cn".equals(email_array)) {// 电信邮箱
				mailUrl = "webmail2.189.cn/webmail/";
			} else if ("qq.com".equals(email_array)) {// qq邮箱
				mailUrl = "mail.qq.com";
			} else if ("yahoo.com".equals(email_array)) {// 雅虎邮箱
				mailUrl = "mail.cn.yahoo.com";
			} else if ("yahoo.cn".equals(email_array)) {// 雅虎邮箱
				mailUrl = "mail.cn.yahoo.com";
			} else if ("yahoo.com.cn".equals(email_array)) {// 雅虎邮箱
				mailUrl = "mail.cn.yahoo.com";
			} else if ("21cn.com".equals(email_array)) {// 21cn邮箱
				mailUrl = "mail.21cn.com";
			} else if ("eyou.com".equals(email_array)) {// eyou邮箱
				mailUrl = "www.eyou.com";
			} else if ("188.com".equals(email_array)) {// 188邮箱
				mailUrl = "www.188.com";
			} else if ("yeah.net".equals(email_array)) {// yeah邮箱
				mailUrl = "www.yeah.net";
			} else if ("foxmail.com".equals(email_array)) {// foxmail邮箱
				mailUrl = "foxmail.com";
			} else if ("wo.com.cn".equals(email_array)) {// 联通手机邮箱
				mailUrl = "mail.wo.com.cn";
			} else if ("263.net".equals(email_array)) {// 263邮箱
				mailUrl = "www.263.net";
			} else if ("x263.net".equals(email_array)) {// 263邮箱
				mailUrl = "www.263.net";
			} else if ("263.net.cn".equals(email_array)) {// 263邮箱
				mailUrl = "www.263.net";
			} else {
				mailUrl = "mail." + (email.substring(email.indexOf("@") + 1));
			}
		}
		return mailUrl;
	}
	
}

文章最后发布于: 2015-09-11 09:28:41

相关阅读

如何在「付费阅读」这场内容生态大洗牌中抓住红利并实

&#8220;微信付费阅读&#8221;必然是整个微信内容生态的一次大洗牌,多数人会在这场内容革命中失败,因为整个生态中的内容逻辑会发生骤

全局负载均衡(GSLB)的实现方案

What is GSLB Global Server Load Balancing 中文:全局负载均衡 SLB(Server load balancing)是对集群内物理主机的负载均衡,而GSL

中值滤波--python实现

中值滤波介绍 中值滤波法是一种非线性平滑技术,它将每一像素点的灰度值设置为该点某邻域窗口内的所有像素点灰度值的中值。中值滤

OA系统:实现员工签到表导出xls

一、准备poiApache POI是Apache软件基金会的开放源码函式库,POI提供API给Java程序对Microsoft Office格式档案读和写的功能。二、

c语言实现霍夫曼树

c语言实现霍夫曼树 #include<stdio.h> #include<string.h> #include<stdlib.h> typedef struct { char value; int weight;

分享到:

栏目导航

推荐阅读

热门阅读