Guest User

Untitled

a guest
Oct 29th, 2018
273
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.84 KB | None | 0 0
  1. import java.time.LocalDateTime;
  2. import java.util.Properties;
  3. import java.util.Random;
  4.  
  5. import javax.mail.Message;
  6. import javax.mail.MessagingException;
  7. import javax.mail.PasswordAuthentication;
  8. import javax.mail.Session;
  9. import javax.mail.Transport;
  10. import javax.mail.internet.InternetAddress;
  11. import javax.mail.internet.MimeMessage;
  12. import javax.servlet.http.HttpServletRequest;
  13. import javax.servlet.http.HttpSession;
  14.  
  15. public class OTPMail {
  16.  
  17. static char[] OTP(int len)
  18. {
  19. System.out.println("Generating OTP using random() : ");
  20. // Using numeric values
  21. String numbers = "0123456789";
  22. // Using random method
  23. Random rndm_method = new Random();
  24. char[] otp = new char[len];
  25. for (int i = 0; i < len; i++)
  26. {
  27. // Use of charAt() method : to get character value
  28. // Use of nextInt() as it is scanning the value as int
  29. otp[i] =
  30. numbers.charAt(rndm_method.nextInt(numbers.length()));
  31. }
  32. return otp;
  33. }
  34. public static void main(String[] args)
  35. {
  36. int length = 4;
  37. char[] OTP = OTP(length);
  38. System.out.print("Generated OTP is: ");
  39. System.out.println(OTP);
  40. String OTPString = String.valueOf(OTP);
  41. //send an email
  42. String messageForMail = "Your OTP for <company name>is: " + OTPString;
  43.  
  44. //update admin mail and password here
  45.  
  46.  
  47. final String username = "shop@<ownDomain>.com";
  48. final String password = "<passowrd>";
  49.  
  50. Properties props = new Properties();
  51. props.put("mail.smtp.auth", "true");
  52. props.put("mail.smtp.starttls.enable", "true");
  53. props.put("mail.smtp.host", "smtp.gmail.com");
  54. props.put("mail.smtp.port", "587");
  55.  
  56. Session session = Session.getInstance(props,
  57. new javax.mail.Authenticator() {
  58. protected PasswordAuthentication getPasswordAuthentication() {
  59. return new PasswordAuthentication(username, password);
  60. }
  61. });
  62.  
  63. try {
  64.  
  65. Message message = new MimeMessage(session);
  66. //message.setFrom(new InternetAddress("Kisna"));
  67.  
  68. //update recipient mail id here.
  69. message.setRecipients(Message.RecipientType.TO,
  70. InternetAddress.parse("<mailId>@gmail.com"));
  71. message.setSubject("OTP");
  72. message.setText(messageForMail);
  73.  
  74. Transport.send(message);
  75.  
  76. System.out.println("OTP sent to mail");
  77. //check the time when mail is sent
  78.  
  79. } catch (MessagingException e) {
  80. throw new RuntimeException(e);
  81. }
  82.  
  83. }
  84.  
  85. }
Add Comment
Please, Sign In to add comment