Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.time.LocalDateTime;
- import java.util.Properties;
- import java.util.Random;
- import javax.mail.Message;
- import javax.mail.MessagingException;
- import javax.mail.PasswordAuthentication;
- import javax.mail.Session;
- import javax.mail.Transport;
- import javax.mail.internet.InternetAddress;
- import javax.mail.internet.MimeMessage;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpSession;
- public class OTPMail {
- static char[] OTP(int len)
- {
- System.out.println("Generating OTP using random() : ");
- // Using numeric values
- String numbers = "0123456789";
- // Using random method
- Random rndm_method = new Random();
- char[] otp = new char[len];
- for (int i = 0; i < len; i++)
- {
- // Use of charAt() method : to get character value
- // Use of nextInt() as it is scanning the value as int
- otp[i] =
- numbers.charAt(rndm_method.nextInt(numbers.length()));
- }
- return otp;
- }
- public static void main(String[] args)
- {
- int length = 4;
- char[] OTP = OTP(length);
- System.out.print("Generated OTP is: ");
- System.out.println(OTP);
- String OTPString = String.valueOf(OTP);
- //send an email
- String messageForMail = "Your OTP for <company name>is: " + OTPString;
- //update admin mail and password here
- final String username = "shop@<ownDomain>.com";
- final String password = "<passowrd>";
- Properties props = new Properties();
- props.put("mail.smtp.auth", "true");
- props.put("mail.smtp.starttls.enable", "true");
- props.put("mail.smtp.host", "smtp.gmail.com");
- props.put("mail.smtp.port", "587");
- Session session = Session.getInstance(props,
- new javax.mail.Authenticator() {
- protected PasswordAuthentication getPasswordAuthentication() {
- return new PasswordAuthentication(username, password);
- }
- });
- try {
- Message message = new MimeMessage(session);
- //message.setFrom(new InternetAddress("Kisna"));
- //update recipient mail id here.
- message.setRecipients(Message.RecipientType.TO,
- InternetAddress.parse("<mailId>@gmail.com"));
- message.setSubject("OTP");
- message.setText(messageForMail);
- Transport.send(message);
- System.out.println("OTP sent to mail");
- //check the time when mail is sent
- } catch (MessagingException e) {
- throw new RuntimeException(e);
- }
- }
- }
Add Comment
Please, Sign In to add comment