Java之邮件发送以及有效邮箱验证

一 邮件发送

maven直接在pom.xml引入

        
            javax.mail
            mail
            1.4.7
        

1 发送邮件第一步:设置发送邮件的邮箱

package com.apk.openUser.utils;

import java.util.List;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;




public class MailUtil {
	public Session getSession(String sender,String password){
		Session session;
		try {
			Properties props = new Properties();
			// 发送服务器需要身份验证  
	        props.setProperty("mail.smtp.auth", "true");  
	        // 设置邮件服务器主机名 ,我这里用的qq企业邮箱作为发件人的 
	        props.setProperty("mail.host", "smtp.exmail.qq.com");  
	        // 发送邮件协议名称  
	        props.setProperty("mail.transport.protocol", "smtp"); 
	        // 设置环境信息  
	        MyAuthenricator authenricator = new MyAuthenricator(sender,password);
	        session = Session.getInstance(props, authenricator);
		} catch (Exception e) {
			// TODO: handle exception
			session = null;
		}
        return session;
	}
	 /** 
     * 客户端程序自己实现Authenticator子类用于用户认证 
     */  
    static class MyAuthenricator extends Authenticator{  
        String user=null;  
        String pass="";  
        public MyAuthenricator(String user,String pass){  
            this.user=user;  
            this.pass=pass;  
        }  
        @Override  
        protected PasswordAuthentication getPasswordAuthentication() {  
            return new PasswordAuthentication(user,pass);  
        }  
          
    }  
    /**
     * 收件人邮箱格式校验
     * @param receivers
     * @return
     */
    public Boolean compileEmail(List receivers){
    	String check = "^([a-z0-9A-Z]+[-|_|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
    	Pattern regex = Pattern.compile(check);   
    	for(String  receiver : receivers){
    		 Matcher matcher = regex.matcher(receiver); 
    		 boolean isMatched = matcher.matches();
    		 if(!isMatched) return false;
    	}
    	return true;
    }
}

 2 设置发送邮件的相关信息

package com.apk.openUser.utils;

import java.io.File;
import java.security.SecureRandom;
import java.util.Date;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message.RecipientType;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;

public class MailSender {
    private Session session;
	 /**
     * 
     * @param sender 发送者邮箱
     * @param receiver 收件人邮箱
     * @param subject 邮件主题
     * @param content 邮件内容
     * @throws Exception
     */
    public  void send(String sender, String receiver, String subject, String content,String password) throws Exception {
		//服务器认证
    	try{
    		System.out.println("sen:"+sender);

    		MailUtil mailUtil = new MailUtil();
    		session = mailUtil.getSession(sender, password);
    		MimeMessage message = new MimeMessage(session);
    		message.setFrom(new InternetAddress(sender));
    		System.out.println(message.getFrom());
    		message.setRecipient(RecipientType.TO, new InternetAddress(receiver));
    		message.setSentDate(new Date());
    		message.setSubject(subject);
    		message.setContent(content, "text/html;charset=UTF-8");
    		Transport.send(message);
    	}catch(Exception e) {
    		e.printStackTrace();
    	}
	}
    //发送含有附件的邮件
    public  void send(String sender, String receiver, String subject, String content,String password,File file,String name) throws Exception {
		//服务器认证
    	MailUtil mailUtil = new MailUtil();
    	session = mailUtil.getSession(sender, password);
    	MimeMessage message = new MimeMessage(session);
    	message.setFrom(new InternetAddress(sender));
    	message.setRecipient(RecipientType.TO, new InternetAddress(receiver));
    	message.setSentDate(new Date());
    	message.setSubject(subject);
    	
    	//添加邮件正文
    	BodyPart contentPart = new MimeBodyPart();
    	// 消息
    	//contentPart.setText(content);
    	contentPart.setContent(content, "text/html;charset=UTF-8");
    	 // 创建多重消息
    	Multipart multipart = new MimeMultipart();
    	// 设置文本消息部分
    	multipart.addBodyPart(contentPart);
    	//附件
    	contentPart = new MimeBodyPart();
    	DataSource source = new FileDataSource(file);
    	contentPart.setDataHandler(new DataHandler(source));
    	contentPart.setFileName(MimeUtility.encodeWord(name));//保证发送名称含中文不乱码
    	multipart.addBodyPart(contentPart);
    	// 发送完整消息
    	message.setContent(multipart);
    	Transport.send(message,message.getAllRecipients());
    	System.out.println("邮件发送成功!");
	}
    
    public static void main(String[] args) throws Exception{
    	String a = "[email protected]";
        String b = "[email protected]";
        String c = "fasong";
        String d = "账户名/username:初始密码/password:66666666
"; String e = "123456"; String sp = "D:\\upload\\kai hu.docx"; File file = new File(sp); String name = "kai hu.docx"; //new MailSender().send(a,b,c,d,e,file,name); SecureRandom s = SecureRandom.getInstance("SHA1PRNG"); System.out.println(s.nextLong()); } }

二 验证邮箱是否为有效正在使用的邮箱

pom.xml里面加入

        
            dnsjava
            dnsjava
            2.1.7
        

        
            commons-net
            commons-net
            3.6
        

验证类如下:

package com.apk.openUser.utils;

import java.io.IOException;
import org.apache.commons.net.smtp.SMTPClient;

import org.apache.commons.net.smtp.SMTPReply;

import org.xbill.DNS.Lookup;

import org.xbill.DNS.MXRecord;

import org.xbill.DNS.Record;

import org.xbill.DNS.Type;

 

public class CheckEmailUtil {

	

	public static final String SENDER_EMAIL = "[email protected]";//"[email protected]";

	public static final String SENDER_EMAIL_SERVER = SENDER_EMAIL.split("@")[1];//"domain.com";

	

	

	/**

	 * 

	 * @param email  The recipient's email address, it need to be validate if it is real exists or doesn't exists.

	 * @return True if email is real exists, false if not.

	 */

	public boolean checkEmailMethod(String email) {

		if (!email.matches("[\\w\\.\\-]+@([\\w\\-]+\\.)+[\\w\\-]+")) {

			System.err.println("Format error");

			return false;

		}

 

		String log = "";

		String host = "";

		String hostName = email.split("@")[1];

		Record[] result = null;

		SMTPClient client = new SMTPClient();

		client.setConnectTimeout(8000);  //设置连接超时时间,有些服务器比较慢

 

		try {

			// 查找MX记录

			Lookup lookup = new Lookup(hostName, Type.MX);

			lookup.run();

			if (lookup.getResult() != Lookup.SUCCESSFUL) {

				log += "找不到MX记录\n";

				return false;

			} else {

				result = lookup.getAnswers();

			}

/*

			 if(result.length > 1) { // 优先级排序

	                List arrRecords = new ArrayList();

	                Collections.addAll(arrRecords, result);

	                Collections.sort(arrRecords, new Comparator() {

	                    

	                    public int compare(Record o1, Record o2) {

	                        return new CompareToBuilder().append(((MXRecord)o1).getPriority(), ((MXRecord)o2).getPriority()).toComparison();

	                    }

	                    

	                });

	                host = ((MXRecord)arrRecords.get(0)).getTarget().toString();

	            }

 * 

 */

			// 连接到邮箱服务器

			

			for (int i = 0; i < result.length; i++) {

				System.out.println(result[i].getAdditionalName().toString());

				System.out.println(((MXRecord)result[i]).getPriority());

			}

			int count=0;  

//			String tempLog ="";

			for (int i = 0; i < result.length; i++) {

				log="";

				host = result[i].getAdditionalName().toString();

				try{

					client.connect(host);	//连接到接收邮箱地址的邮箱服务器

				}catch(Exception e){		//捕捉连接超时的抛出的异常

					count++;

					if(count>=result.length){	//如果由MX得到的result服务器都连接不上,则认定email无效

						log +="Connect mail server timeout...\n";

						return false;

					}

				}

				

				if (!SMTPReply.isPositiveCompletion(client.getReplyCode())) {	//服务器通信不成功

					client.disconnect();

					continue;

				} else {

					log += "MX record about " + hostName + " exists.\n";

					log += "Connection succeeded to " + host + "\n";

					log += client.getReplyString();

					

					// HELO <$SENDER_EMAIL_SERVER>   //domain.com

					try{

						client.login(SENDER_EMAIL_SERVER);   //这一步可能会出现空指针异常

					}catch(Exception e){

						return false;

					}

					log += ">HELO "+SENDER_EMAIL_SERVER+"\n";

					log += "=" + client.getReplyString();

					

					client.setSender(SENDER_EMAIL);

					if(client.getReplyCode()!=250){		//为解决hotmail有的MX可能出现=550 OU-001 (SNT004-MC1F43) Unfortunately, messages from 116.246.2.245 weren't sent.

						client.disconnect();

						continue;							//把client.login 和client.setSender放在循环体内,这样所有的如果某mx不行就换其他mx,但这样会对无效的邮箱进行所有mx遍历,耗时

					}

					log += ">MAIL FROM: <"+SENDER_EMAIL+">\n";

					log += "=" + client.getReplyString();

					// RCPT TO: <$email>

					try{

						client.addRecipient(email);

					}catch(Exception e){

						return false;

					}

					log += ">RCPT TO: <" + email + ">\n";

					log += "=" + client.getReplyString();

					

					//最后从收件邮箱服务器返回true,说明服务器中能够找到此收件地址,邮箱有效

					if (250 == client.getReplyCode()) {

						return true;

					}

					client.disconnect();

					

				}

			}

//			log+=tempLog;

//			log += ">MAIL FROM: <"+SENDER_EMAIL+">\n";

//			log += "=" + client.getReplyString();

//			

//			// RCPT TO: <$email>

//			try{

//				client.addRecipient(email);

//			}catch(Exception e){

//				return false;

//			}

//			log += ">RCPT TO: <" + email + ">\n";

//			log += "=" + client.getReplyString();

//			

//			//最后从收件邮箱服务器返回true,说明服务器中能够找到此收件地址,邮箱有效

//			if (250 == client.getReplyCode()) {

//				return true;

//			}

		} catch (Exception e) {

			e.printStackTrace();

		} finally {

			try {

				client.disconnect();

			} catch (IOException e) {

			}

			// print log

			System.out.println(log);

		}

		return false;

	}

	

	/**

	 * This method is more accurate than checkEmailMethod(String email);

	 * 

	 * @param email  The recipient's email address, it need to be validate if it is real exists or doesn't exists.

	 * @return True if email is real exists, false if not.

	 */

	public boolean checkEmail(String email){

		if(email.split("@")[1].equals("qq.com")){

			if( checkEmailMethod(email) && checkEmailMethod(email) && checkEmailMethod(email)){

				return true;

			}else{

				return false;

			}

		}

		return checkEmailMethod(email);

	}

	public static void main(String[] args) {

		CheckEmailUtil ce = new CheckEmailUtil();

		if(ce.checkEmail("[email protected]")){

			System.out.println("true");

		}else{

			System.out.println("false");

		}

	}

 

}

 

 

你可能感兴趣的:(java)