java application: send mail to user registered mailbox

Implement functionality

Forget password, successful registration, etc. Send authentication code information or registration information to the user.

operation flow

Forget password:

1. Verify that the mailbox has been registered;

Send verification code to mailbox;

3. Verify that the verification code is correct;

4. Reset the password;

I'm going to focus on the code for sending e-mail. Other business codes need to be typed by you.Before writing the code, it is recommended that you apply for a mailbox from another company, such as 163, and obtain the authorization number for that mailbox.This is the authorization code acquisition for 163 mailbox.

Step 1:

  

Step 2:

  

Step 3:

  

Step 4: Just set the authorization number, so there are no screenshots.After setting the authorization number, you record the authorization number and SMTP server: smtp.163.com.The SMTP server address can be queried in POP3/SMTP/IMAP.The 163 mailbox is smtp.163.com, which you can use directly.

Appendix: Code

1. js code

 1 //Query for Mailbox Existence
 2 $("#checkEm").click(function(){
 3               content = $("#content").val();
 4               
 5               if(content.length == 0 || content.length == ""){
 6                   alert("Please enter your mailbox");
 7                   return;
 8               }else if(checkContent(content) == 0){
 9                   alert("The mailbox you entered is not in the correct format!")
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("The mailbox you entered is not registered yet!");
25                           }
26                       }
27                   })
28               }
29           })
 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           })

2. action Processing Code

 1 // Generate 6-bit random numbers before sending verification codes
 2 private String randomBiocuration(){  
 3         String result="";
 4         for(int i=0;i<6;i++){
 5         //Generate 97-122 Of int Integer of type
 6         int intValue=(int)(Math.random()*9+1);
 7         //take intValue Forced conversion to char Type followed by resul behind
 8         result=result+String.valueOf(intValue);
 9         }
10         return result;
11     }
 1 // Check Mailbox Existence
 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     }
 1 //Send Mail
 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('Sender Mailbox', 'Password for sender's mailbox', 'Recipient Mailbox', 'Mailbox Title', 'Mailbox Content', 'Sender Mailbox Smtp address');
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     }

3. Service Impl Code

 1 // Service Layer Implementation Class
 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             // Set up a mail session
15             Properties props = new Properties(); // Used to store keys in a file-Value pairs, where the keys and values are separated by equal signs,
16             // Store information about the outgoing mail server
17             props.put("mail.smtp.host", smtp);
18             // Simultaneously validated
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             // Create a new mail session based on properties
25             Session s = Session.getInstance(props);
26             s.setDebug(false); // If he does, he will print some debugging information.
27 
28             // New Message Object from Mail Session
29             MimeMessage message = new MimeMessage(s);
30             // Set up mail
31             InternetAddress from = new InternetAddress(emailName); // Sender Mailbox
32             message.setFrom(from); // Set the sender's address
33             // 
34             // //Set up recipients,And set its receive type to TO
35             InternetAddress to = new InternetAddress(email); //Recipient Mailbox
36             message.setRecipient(Message.RecipientType.TO, to);
37 
38             // Set Title
39             message.setSubject(title); 
40 
41             // Set up message content
42             message.setContent(content,"text/html;charset=gbk"); // Send out HTML mail
43                                                 
44             // Set the sending time
45             message.setSentDate(new Date());
46 
47             // Store mail information
48             message.saveChanges();
49         
50             // Send Mail    
51             Transport transport = s.getTransport("smtp");
52             // with smtp Login Mailbox by Mode,The first parameter is the mail server used to send mail SMTP address,The second parameter is the user name,The third parameter is the password
53             transport.connect(smtp,emailName,password);
54             // Send Mail,The second parameter is all addresses that have been set for recipients
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 }

On the way of life, you have traveled a long time. When you look back suddenly, you will find that every section and time you have traveled in the past is wonderful and unique.In fact, not to live up to every passing time is the greatest fullness and regret of life.

Tags: Java Session JSON Mobile SSL

Posted on Wed, 20 May 2020 09:19:31 -0700 by nikes90