• java应用:向用户注册的邮箱发送邮件


    实现功能

      忘记密码,注册成功等向用户发送验证码信息或注册信息。

    业务流程

      忘记密码:

      1、验证邮箱是否注册过;

      2、向邮箱发送验证码;

      3、验证验证码是否正确;

      4、重新设置密码;

      我这里着重介绍发送邮件的代码,其他的业务代码需要大家自己去敲。在写代码之前,建议先去申请一个163等其他公司的邮箱,并且获取该邮箱的授权码。这里介绍一下163邮箱的授权码获取。

      第一步:

      

      第二步:

      

      第三步:

      

      第四步:设置授权码就好,这里就不截图了。设置授权码后,你要记录授权码和SMTP服务器: smtp.163.com。SMTP服务器地址可以在POP3/SMTP/IMAP 查询到。163邮箱就是 smtp.163.com,可以直接拿去用。

     附录:代码

      一、js代码

     1 //查询邮箱是否存在
     2 $("#checkEm").click(function(){
     3               content = $("#content").val();
     4               
     5               if(content.length == 0 || content.length == ""){
     6                   alert("请输入您的邮箱");
     7                   return;
     8               }else if(checkContent(content) == 0){
     9                   alert("您输入的邮箱格式不正确!")
    10               }else if(checkContent(content) == 1){
    11                   inputType = "email";
    12                   $.ajax({
    13                       url:"<%=serverIp%>/webcons.do?method=checkEmail",
    14                       dataType:"text",
    15                       type:"get",
    16                       data:"fromWhere=<%=code%>&email="+content+"&type=1&isCountry=2",
    17                       async:false,
    18                       success:function(result){
    19                           console.log(result)
    20                           if(result == 1){
    21                               $("#checkTable").hide();
    22                               $("#codeTable").show();
    23                           }else{
    24                               alert("您输入的邮箱还没有注册!");
    25                           }
    26                       }
    27                   })
    28               }
    29           })
    View Code
     1 $("#sendSms").click(function(){
     2             if(inputType == "email"){
     3                 $.ajax({
     4                     url:"<%=serverIp%>/webcons.do?sendEmailCode",
     5                     type:"post",
     6                     data:"email="+content+"&code=<%=code%>",
     7                     dataType:"json",
     8                     async:false,
     9                     success:function(result){
    10                         if(result.state == 1){
    11                             timer = window.setInterval("timego()",1000);
    12                         }
    13                     }
    14                 })
    15             }else if(inputType == "mobile"){
    16                 $.ajax({
    17                     url:"<%=serverIp%>/webcons.do?sendMobileCode",
    18                     type:"post",
    19                     data:"mobile="+content+"&code=<%=code%>",
    20                     dataType:"json",
    21                     async:false,
    22                     success:function(result){
    23                         if(result.state == 1){
    24                             if(result.state == 1){
    25                                 timer = window.setInterval("timego()",1000);
    26                             }
    27                         }else{
    28                             alert(result.msg);
    29                         }
    30                     }
    31                 })
    32             }
    33           })
    View Code

      二、action处理代码

     1 // 在发送验证码之前,先生成6位随机数
     2 private String randomBiocuration(){  
     3         String result="";
     4         for(int i=0;i<6;i++){
     5         //生成97-122的int型的整型
     6         int intValue=(int)(Math.random()*9+1);
     7         //将intValue强制转化成char类型后接到resul后面
     8         result=result+String.valueOf(intValue);
     9         }
    10         return result;
    11     }
    View Code
     1 // 检查邮箱是否存在
     2 @RequestMapping(params = "method=checkEmailBiocuration", method = RequestMethod.GET)
     3     public void checkEmailBiocuration(String email, int isCountry,
     4             HttpServletRequest request, HttpServletResponse response) {
     5         try {
     6             String fromWhere = request.getParameter("fromWhere") == null?null:request.getParameter("fromWhere");
     7             String type = request.getParameter("type") == null ? "1" : request
     8                     .getParameter("type"); 
     9             int type1 = Integer.parseInt(type);
    10             UserInfo userInfo = null;
    11             if(fromWhere != null){
    12                 userInfo = webService.getuserInfoByEmail(email,type1,fromWhere);
    13             }else{
    14                 userInfo = webService.getUserInfoByEmail(email, type1);
    15             }
    16             if (userInfo != null) {
    17                 response.getWriter().print("1");
    18             } else {
    19                 response.getWriter().print("0");
    20             }
    21         } catch (Exception e) {
    22             e.printStackTrace();
    23         }
    24     }
    View Code
     1 //发送邮件
     2 @RequestMapping(params = "sendEmailCodeBiocuration",method = RequestMethod.POST)
     3     public void sendEmailCodeBiocuration(String email,String code,HttpServletResponse response){
     4         try {
     5             Conferences cons = webService.getConferencesByCode(code);
     6             JSONObject result = new JSONObject();
     7             ConPasswordBack passwordBack = webService.getPasswordBackByType(1,cons.getConferencesId());
     8             if(passwordBack != null){
     9                 String emailCodeStr = randomBiocuration();
    10                 EmailPublic emailPublic = webService.getEmailPublicById(passwordBack.getEmailPublicId());
    11                 EmailModel emailModel = webService.getEmailModelById(passwordBack.getEmailModelId());
    12                 EmailUtil.init().sendEmail('发件人邮箱', ‘发件人邮箱的密码’, ‘收件人邮箱’, ‘邮箱标题’, ‘邮箱内容’, ‘发件人邮箱Smtp地址’);
    13                 EmailCode emailCode = webService.getEmailCodeByConId(email,cons.getConferencesId());
    14                 if(emailCode == null){
    15                     emailCode = new EmailCode();
    16                 }
    17                 emailCode.setCode(emailCodeStr);
    18                 emailCode.setCreateTime(new Date());
    19                 emailCode.setConferencesId(cons.getConferencesId());
    20                 emailCode.setEmail(email);
    21                 webService.saveObject(emailCode);
    22             }
    23             result.accumulate("state", 1);
    24             writeJson(response, result.toString());
    25         } catch (Exception e) {
    26             e.printStackTrace();
    27         }
    28     }
    View Code

      三、serviceImpl 代码

     1 // 服务层实现类
     2 public class EmailUtil {
     3     private static EmailUtil emailUtil = null;
     4     public static EmailUtil init(){
     5         if(emailUtil == null){
     6             emailUtil = new EmailUtil();
     7         }
     8         return emailUtil;
     9     }
    10     public  boolean sendEmail(String emailName,String password,String email,String title,String content,String smtp) {
    11         try {
    12             MailSSLSocketFactory sf = new MailSSLSocketFactory();
    13             sf.setTrustAllHosts(true);
    14             // 建立邮件会话
    15             Properties props = new Properties(); // 用来在一个文件中存储键-值对的,其中键和值是用等号分隔的,
    16             // 存储发送邮件服务器的信息
    17             props.put("mail.smtp.host", smtp);
    18             // 同时通过验证
    19             props.put("mail.smtp.auth", "true");
    20             props.put("mail.smtp.port", "465");
    21             props.put("mail.smtp.ssl.enable", "true");
    22             props.put("mail.smtp.ssl.socketFactory", sf);
    23             props.setProperty("mail.transport.protocol", "smtp");
    24             // 根据属性新建一个邮件会话
    25             Session s = Session.getInstance(props);
    26             s.setDebug(false); // 有他会打印一些调试信息。
    27 
    28             // 由邮件会话新建一个消息对象
    29             MimeMessage message = new MimeMessage(s);
    30             // 设置邮件
    31             InternetAddress from = new InternetAddress(emailName); // 发件人邮箱
    32             message.setFrom(from); // 设置发件人的地址
    33             // 
    34             // //设置收件人,并设置其接收类型为TO
    35             InternetAddress to = new InternetAddress(email); //收件人邮箱
    36             message.setRecipient(Message.RecipientType.TO, to);
    37 
    38             // 设置标题
    39             message.setSubject(title); 
    40 
    41             // 设置信件内容
    42             message.setContent(content,"text/html;charset=gbk"); // 发送HTML邮件
    43                                                 
    44             // 设置发信时间
    45             message.setSentDate(new Date());
    46 
    47             // 存储邮件信息
    48             message.saveChanges();
    49         
    50             // 发送邮件    
    51             Transport transport = s.getTransport("smtp");
    52             // 以smtp方式登录邮箱,第一个参数是发送邮件用的邮件服务器SMTP地址,第二个参数为用户名,第三个参数为密码
    53             transport.connect(smtp,emailName,password);
    54             // 发送邮件,其中第二个参数是所有已设好的收件人地址
    55             transport.sendMessage(message, message.getAllRecipients());
    56             transport.close();
    57             return true;
    58         } catch (Exception e) {
    59             e.printStackTrace();
    60             return false;
    61         }
    62     }
    63 }
    View Code

    人生的路上,跋涉了很久,当蓦然回首,会发觉从前走过的每一段路、经历过的每一段时光都是美好奇妙、独一无二的。其实,不曾辜负走过的每一份光阴,就是生命最大的圆满与无憾。

      

  • 相关阅读:
    LeetCode:删除链表中的节点【203】
    精益创业和画布实战(1):变革家,让天下没有难懂的生意
    怎么投资理财,如果有且仅有100万本金?
    怎么投资理财,如果有且仅有100万本金?
    Java集合——HashMap、HashTable以及ConCurrentHashMap异同比较
    View绘制详解,从LayoutInflater谈起
    Java线程和多线程(七)——ThreadLocal
    跳槽谋发展:人生发展的一些思考和最近找工作的坎坷经历
    跳槽谋发展:人生发展的一些思考和最近找工作的坎坷经历
    三个案例带你看懂LayoutInflater中inflate方法两个参数和三个参数的区别
  • 原文地址:https://www.cnblogs.com/jichuang/p/8043732.html
Copyright © 2020-2023  润新知