0

my problem is that in below code as long as to has the @ in it there is no error! For example if I enter x@y there is no error! How can I show an error when the email address doesn't exists or domain name is incorrect?

public void sendMail(String content, String to, String subject) {

        MimeMessage message = mailSender.createMimeMessage();

       try{
            MimeMessageHelper helper = new MimeMessageHelper(message, true);

            helper.setFrom(simpleMailMessage.getFrom());
            helper.setTo(to.split(","));
            helper.setSubject(subject);
            helper.setText(String.format(simpleMailMessage.getText(), content));
         }catch (MessagingException e) {
                   e.printStackTrace();

         }
         mailSender.send(message);
         System.out.rpint("email was sent to "+to+" successfully");
}
StarsSky
  • 6,721
  • 6
  • 38
  • 63
Sara
  • 2,308
  • 11
  • 50
  • 76

3 Answers3

0

Try this regex:

^[_A-Za-z0-9-\+]+(\.[_A-Za-z0-9-]+)@[A-Za-z0-9-]+(\.[A-Za-z0-9]+)(\.[A-Za-z]{2,})$;

http://www.mkyong.com/

ruhungry
  • 4,506
  • 20
  • 54
  • 98
0

For general checking if an email address could be valid (static validation of the format) you can use for example apache commons (see What is the best Java email address validation method?)

For validation if an email address exist, a common way is to send an email to this address, with an double opt in token, that the user need to click, to confirm that he is the owner of the mail account.

Community
  • 1
  • 1
Ralph
  • 118,862
  • 56
  • 287
  • 383
0

What you can do is to:

1.use a regex to validate the input : eg. ^[_A-Za-z0-9-+]+(.[_A-Za-z0-9-]+)@[A-Za-z0-9-]+(.[A-Za-z0-9]+)(.[A-Za-z]{2,})$

2.check the MX records : http://webtools.live2support.com/nt_mxrecords.php

In java you can do this by using dnsjava library.

public Record[] lookupMxRecords(String domain) throw TextParseException

{
   final Lookup dnsLookup = new Lookup(domain, Type.MX);
   return dnsLookup.run();
 }
sergiu
  • 389
  • 1
  • 7