简体   繁体   中英

send verification code/link from java REST service

I have a dropwizard REST service and I am trying to implement sending verification email link/code once the user signup.

I have a field in my database in the user table called is_active that denotes whether the user is verified or not.

  private String email;
  @JsonProperty
  private String password;
  @JsonProperty
  private String name;
  @JsonProperty
  private String surname;
  @JsonProperty
  private boolean isActive;

I am trying to figure out whats the right way to send this verification email, I have written a class that sends SMTP emails to the user but I am bit skeptical about whether its correct way of sending email or not?

public class SendEmail  
{  
 public static void main(String [] args){  
      String to = "customer@gmail.com";
      String from = "mycompany@gmail.com";  
      String host = "localhost";

      Properties properties = System.getProperties();  
      properties.setProperty("mail.smtp.host", host);  
      Session session = Session.getDefaultInstance(properties);  
      try{  
         MimeMessage message = new MimeMessage(session);  
         message.setFrom(new InternetAddress(from));  
         message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));  
         message.setSubject("verification email");  
         message.setText("Hello, this is sample verification email ");  

         Transport.send(message);  
         System.out.println("message sent successfully....");  

      }catch (MessagingException mex) {mex.printStackTrace();}  
   }  
}  

Is this how I should be implementing or use some external provider like sendgrid for this?

Your approach is fine. Some things to consider:

  • How many emails does the SMTP server accept in which timeframe? Some SMPT servers apply rate limits which may cause message sending to fail. Your code should recognize this and have a strategy to perhaps resend the email again at a later time.
  • The verification link in the email body should contain a unique secret that can only be used to verify a specific user. This secret will have to be stored and associated with the user.
  • The link should not contain anthing like the user ID or name. Such links are easily faked.
  • The REST API that is called by clicking on a verification link should take the secret and look up the user associated with it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM