javamail发送6位数认证码到邮箱

来源:互联网 发布:电话号码数据库购买 编辑:程序博客网 时间:2024/06/05 14:51

    主要 实现忘记密码时向登陆用户的对应邮箱中发送一封6位随机数的认证码。

    开始导入activation.jar和mail.jar。

   下面就是相关配置文件及发送邮件的类

MAIL 类

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.Random;
import javax.mail.Session;
import javax.mail.Message;
import javax.mail.Transport;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.InternetAddress;
import javax.mail.Authenticator;
import javax.servlet.http.HttpSession;
import org.apache.struts2.ServletActionContext;
import com.ynashk.CMSOTS.bo.UserBo;
 
//email发送
public class Emailsend{
     public String email(){
         InputStream in = ReadProperties.class.getClassLoader().getResourceAsStream("messageResource_en_US.properties");
         Random random = new Random();
         String auth = "";  //邮件内容
          for (int i = 0; i < 6; i++) {
             auth += random.nextInt(10);
          }
          HttpSession session = ServletActionContext.getRequest().getSession();
          String to = new UserBo().getEmailByUserName((String)session.getAttribute("resetusername"));//收信邮箱
         //邮件主题
         Properties properties = new Properties();//创建Properties对象
         try {
            properties.load(in);
        } catch (IOException e1) {
            
            e1.printStackTrace();
        }
         properties.setProperty("mail.transport.protocol", "smtp");//设置传输协议
         properties.put("mail.smtp.host", "smtp.163.com");//设置发信邮箱的smtp地址
         properties.setProperty("mail.smtp.auth", "true"); //验证
         String from = properties.getProperty("mail.address");
         String username = properties.getProperty("mail.username");
         String password = properties.getProperty("mail.password");
         String subject = properties.getProperty("mail.subject");
         String title = properties.getProperty("mail.title");
         Authenticator authen = new MyAuthenticator(username,password); //使用验证,创建一个Authenticator
         Session s = Session.getInstance(properties, authen);//根据Properties,Authenticator创建Session
         try{
                 Message message = new MimeMessage(s);//Message存储发送的电子邮件信息
                 message.setFrom(new InternetAddress(from));
                 message.setRecipient(Message.RecipientType.TO,new InternetAddress(to));//设置收信邮箱
                 message.setSubject(title);//设置主题
                 message.setText(subject+auth+"。");//设置内容
                 Transport.send(message);//发送
             }catch(MessagingException e){
                 e.printStackTrace();
                 auth = "";
             }
                 return auth;
             }

}


MyAuthenticator类

import javax.mail.*;   
 
//创建传入身份验证信息的 Authenticator类
public class MyAuthenticator extends Authenticator {
    private String user;     
    private String pwd;      
    public MyAuthenticator(String user, String pwd) {
        this.user = user;         
        this.pwd = pwd;     
}      
@Override    
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(user, pwd);     
    }
}


ReadProperties类

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Collection;
import java.util.Iterator;
import java.util.Properties;


public class ReadProperties {

    public static void main(String[] args) {
        File file = new File("c:/test.properties");
        FileInputStream inputStream = null;
        try {
            inputStream = new FileInputStream(file);

        } catch (FileNotFoundException e){
// TODO Auto-generated catch block
            e.printStackTrace();
        }
        Properties pro = new Properties();
        try {
            pro.load(inputStream);//Properties对象以生成,包括文件中的数据。
        } catch (IOException e) {
// TODO Auto-generated catch block
            e.printStackTrace();
        }
        Collection<Object> keySet = pro.keySet();
            for(Iterator iter = keySet.iterator();iter.hasNext();){
                String key = (String)iter.next();
                System.out.println(key + " : " + pro.getProperty(key));
        }
    }
}


action

public String sendAuthentication(){
        HttpServletRequest request = ServletActionContext.getRequest();
        HttpSession session = ServletActionContext.getRequest().getSession();
        session.setAttribute("resetusername", request.getParameter("user.username"));
        if(userBo.checkUsername(request.getParameter("user.username"))&&this.checkCode()){
            Emailsend es = new Emailsend();
            String a = es.email();
            if(!"".equals(a)){
                Date d = new AddMinut().addDateMinut();
                Date now = new Date();
                int userId = userBo.getUserId(request.getParameter("user.username"));
                int uid = userBo.getUserId(request.getParameter("user.username"));
                if(resetpasswordBo.checkUserId(userId)==true){
                    resetpassword = new ResetPasswordVo();
                    resetpassword.setUserId(uid);
                    resetpassword.setAuth(a);
                    resetpassword.setAuthCreateDatetime(now);
                    resetpassword.setAuthExpireDatetime(d);
                    resetpasswordBo.AddresetPassword(resetpassword);
                }else if(resetpasswordBo.checkUserId(userId)==false){
                    resetpasswordBo.update(userId,a);
                }
                    return SUCCESS;
            }else{
                return INPUT;
            }
        }else{
            return INPUT;
        }        
}


struts.xml

        <!-- 发送认证码到邮箱 -->
        <action name="userSendAuthenticationCode" class="com.ynashk.CMSOTS.action.UserAction" method="sendAuthentication">
            <result name="success" type="redirect">/jsp/trainingcloudUnlogin/reset_password2.jsp</result>
            <result name="input" type="redirect">/jsp/trainingcloudUnlogin/reset_password1.jsp</result>
        </action>


resetpassword.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="resetpassword" >
     <resultMap id="BaseResultMap" type="resetpasswordVo" >
         <id column="id" property="Id" jdbcType="INTEGER" />
         <result column="user_id" property="userId" jdbcType="INTEGER" />
         <result column="authentication_code" property="auth" jdbcType="VARCHAR" />
         <result column="expire_datetime" property="authExpireDatetime" jdbcType="TIMESTAMP" />
         <result column="create_datetime" property="authCreateDatetime" jdbcType="TIMESTAMP"/>
     </resultMap>
    
     <!-- 添加日志 -->
     <insert id="addAuth" parameterType="resetpasswordVo">
         <selectKey keyProperty="Id" order="AFTER" resultType="java.lang.Integer">
            SELECT LAST_INSERT_ID()
        </selectKey>
    insert into reset_password(user_id,authentication_code,expire_datetime,create_datetime)
    values
    (#{userId,jdbcType=INTEGER},#{auth,jdbcType=VARCHAR},#{authExpireDatetime,jdbcType=TIMESTAMP},#{authCreateDatetime,jdbcType=TIMESTAMP})
     </insert>
     <!-- 根据用户名ID查验证码 -->
  <select id="selectAuth" parameterType="resetpasswordVo" resultMap="BaseResultMap">
      select authentication_code from reset_password where user_id = #{userId,jdbcType=INTEGER} and expire_datetime>now();
  </select>
  <!-- 检测用户ID是否存在 -->
  <select id="selectUserId" parameterType="resetpasswordVo" resultMap="BaseResultMap">
      select user_id from reset_password where user_id = #{userId,jdbcType=INTEGER};
  </select>
   <!-- 根据用户ID修改用户信息  -->
  <update id="updateAuth" parameterType="resetpasswordVo" >
      update reset_password set authentication_code=#{auth,jdbcType=VARCHAR},expire_datetime = #{authExpireDatetime,jdbcType=TIMESTAMP},create_datetime=#{authCreateDatetime,jdbcType=TIMESTAMP} where user_Id = #{userId,jdbcType=INTEGER};
      
  </update>
</mapper>


messageResource.properties

mail.address = wgqxxxxxx@163.com
mail.username = wgqxxxxxx@163.com
mail.password = xxxxxxx
mail.subject = Your 6-digit authentication code :
mail.title = CMS Oline Training System Reset Password



0 0
原创粉丝点击