×

Welcome to TagMyCode

Please login or create account to add a snippet.
0
0
 
0
Language: Text
Posted by: Rishabh Narayan
Added: Aug 3, 2021 9:25 AM
Modified: Aug 3, 2021 9:28 AM
Views: 3650
Tags: no tags
  1.   public boolean sendEmail(User user) {
  2.         boolean test = false;
  3.  
  4.         String toEmail = user.getEmail();
  5.         String fromEmail = "<youremail>@gmail.com";
  6.         String password = <your password>
  7.  
  8.         try {
  9.  
  10.             // your host email smtp server details
  11.              Properties pr = new Properties(); //imposto il server per la spedizione
  12.  
  13. pr.put("mail.smtp.host", "smtp.gmail.com");
  14. pr.put("mail.smtp.port", "587");
  15. pr.put("mail.smtp.starttls.enable","true" );
  16. pr.put("mail.smtp.auth", "true" );
  17.  
  18.             //get session to authenticate the host email address and password
  19.             Session session = Session.getInstance(pr, new Authenticator() {
  20.                 @Override
  21.                 protected PasswordAuthentication getPasswordAuthentication() {
  22.                     return new PasswordAuthentication(fromEmail, password);
  23.                 }
  24.             });
  25.  
  26.             //set email message details
  27.             Message mess = new MimeMessage(session);
  28.  
  29.                 //set from email address
  30.             mess.setFrom(new InternetAddress(fromEmail));
  31.                 //set to email address or destination email address
  32.             mess.setRecipient(Message.RecipientType.TO, new InternetAddress(toEmail));
  33.                
  34.                 //set email subject
  35.             mess.setSubject("User Email Verification");
  36.            
  37.                 //set message text
  38.             mess.setText("Registered successfully.Please verify your account using this code: " + user.getCode());
  39.             //send the message
  40.             Transport.send(mess);
  41.            
  42.             test=true;
  43.            
  44.         } catch (Exception e) {
  45.             e.printStackTrace();
  46.         }
  47.  
  48.         return test;
  49.     }