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

一 邮件发送

maven直接在pom.xml引入

        <dependency>
            <groupId>javax.mail</groupId>
            <artifactId>mail</artifactId>
            <version>1.4.7</version>
        </dependency>

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<String> 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.securit
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值