0

I am working on user registration function.Now I headed a new problem.

I want to send an Email to user after user done with the Registration.

@PostMapping("registration")
public String registration(Model model,
        @Valid @ModelAttribute("cool") User user,
        BindingResult bindingresult) {

    if (bindingresult.hasErrors()) {
        model.addAttribute("cool", user);
        return "registration";
    }
    model.addAttribute("user", user);
    data.addUser(user);

    //------------------------Email----------------//
            // Here I need a solution
    //------------------------Email----------------//
    return "success";
}

For example:

my Email Address is: [email protected]

I want to send an Email from my Email(or from localhost) to User's Email.

2 Answers 2

1

You can use Gmail SMTP via TLS

private static String USER_NAME = "Gmail Username";  // GMail user name (just the part before "@gmail.com")
private static String PASSWORD = "gbxxfgfhujdfqndd"; // GMail password

public static boolean sendEmail(String RECIPIENT, String sub, String title, String body, String under_line_text,
 String end_text) {
 String from = USER_NAME;
 String pass = PASSWORD;
 String[] to = {
  RECIPIENT
 }; // list of recipient email addresses
 String subject = sub;
 Properties props = System.getProperties();
 String host = "smtp.gmail.com";
 props.put("mail.smtp.starttls.enable", "true");
 props.put("mail.smtp.host", host);
 props.put("mail.smtp.user", from);
 props.put("mail.smtp.password", pass);
 props.put("mail.smtp.port", "587");
 props.put("mail.smtp.auth", "true");

 Session session = Session.getDefaultInstance(props);
 MimeMessage message = new MimeMessage(session);

 try {
  message.setFrom(new InternetAddress(from));
  InternetAddress[] toAddress = new InternetAddress[to.length];

  // To get the array of addresses
  for (int i = 0; i < to.length; i++) {
   toAddress[i] = new InternetAddress(to[i]);
  }

  for (int i = 0; i < toAddress.length; i++) {
   message.addRecipient(Message.RecipientType.TO, toAddress[i]);
  }

  message.setSubject(subject);
  BodyPart messageBodyPart = new MimeBodyPart();
  String htmlText = "<div style=\" background-color: white;width: 25vw;height:auto;border: 20px solid grey;padding: 50px;margin:100 auto;\">\n" +
   "<h1 style=\"text-align: center;font-size:1.5vw\">" + title + "</h1>\n" + "<div align=\"center\">" +
   "<h2 style=\"text-align: center;font-size:1.0vw\">" + body + "</h2>" +

   "<h3 style=\"text-align: center;text-decoration: underline;text-decoration-color: red;font-size:0.9vw\">" +
   under_line_text + "</h3><br><h4 style=\"text-align: center;font-size:0.7vw\">" + end_text +
   " </h4></div>";
  messageBodyPart.setContent(htmlText, "text/html");

  Multipart multipart = new MimeMultipart();

  // Set text message part
  multipart.addBodyPart(messageBodyPart);
  message.setContent(multipart);

  Transport transport = session.getTransport("smtp");
  transport.connect(host, from, pass);
  transport.sendMessage(message, message.getAllRecipients());
  transport.close();
 } catch (AddressException ae) {
  ae.printStackTrace();
 } catch (MessagingException me) {
  me.printStackTrace();
 }
 return true;
}

Or Gmail via SSL in which you should add

//change port number
prop.put("mail.smtp.port", "465");
prop.put("mail.smtp.socketFactory.port", "465");
prop.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");

Output:

enter image description here

Also you can change BodyPart accordingly i have included an html responsive template


I recommend you to visit your Google Account and generate a new Application Password , this allows your password field to be encoded and not used as plain text

Otherwise you will come up with this exception

javax.mail.AuthenticationFailedException: 534-5.7.9 Application-specific password required.

Hope it helped!

18
  • Have error message: Could not connect to SMTP host: smtp.gmail.com, port: 465(also with 587). Commented Jun 10, 2020 at 8:50
  • Did you try TLS? port 587 Commented Jun 10, 2020 at 8:51
  • maybe i am doing something wrong,i just copied your code, writed in ''final String username,final String password'' my email address and my password. Commented Jun 10, 2020 at 8:57
  • correct , try to generate an application password as well Commented Jun 10, 2020 at 8:59
  • I updated my answer, check it out if it works for you, i think you should be fine now,you will need an application password from your google account, you can get it from the security tab Commented Jun 10, 2020 at 9:03
0
 String host = "smtp.gmail.com";  
        int port = 587;  
        final String username = "[email protected]";  
        final String password = "your password";  

        Properties props = new Properties();  
        props.put("mail.smtp.host", host);  
        props.put("mail.smtp.auth", "true");  
        props.put("mail.smtp.starttls.enable", "true");  
        props.put("mail.smtp.port", port);  

        Session session = Session.getInstance(props,new Authenticator(){  
              protected PasswordAuthentication getPasswordAuthentication() {  
                  return new PasswordAuthentication(username, password);  
              }} );  

        try {  

        Message message = new MimeMessage(session);  
        message.setFrom(new InternetAddress("[email protected]"));  
        message.setRecipients(Message.RecipientType.TO,   
                        InternetAddress.parse("[email protected]"));  
        message.setSubject("Testing Subject");  
        message.setText("Dear Mail Crawler,\n\n No spam to my email, please!");  

        Transport transport = session.getTransport("smtp");  
        transport.connect(host, port, username, password);  

        Transport.send(message);  

        System.out.println("Done");  

        } catch (MessagingException e) {  
            throw new RuntimeException(e);  
        }  
1
  • I had an error: javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 587. Do you know how to solve it ? I just changed my Internet form home to office,is it the reason? Commented Jun 16, 2020 at 7:36

Not the answer you're looking for? Browse other questions tagged or ask your own question.