How to check mail address is exists or not?

Deepu picture Deepu · Nov 22, 2012 · Viewed 34.2k times · Source

I am sending email through Java using com.sun.mail.smtp.SMTPTransport.

I am successful to send the email, but SMTPTransport not giving any error if I send the mail to invalid email address.

Is there a way to check that given mail address is exists or not?

I dont mean to check the mail address as client side, I need to check as server side.

I found many questions like this on many forums but I am not getting any proper solutions.

My Code is -

String email = "[email protected]";

Properties props = new Properties();
props.put("mail.smtps.host", "mail.myDomain.com");
props.put("mail.smtps.auth", "true");
Session session = Session.getInstance(props, null);

MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress("Mail Demo <[email protected]>"));
msg.setRecipients(Message.RecipientType.TO, email);
msg.setSubject("Mail Example");
msg.setSentDate(new Date(System.currentTimeMillis()));

String txt = "Message Body";

msg.setText(txt);
SMTPTransport st = (SMTPTransport)session.getTransport("smtps");
st.connect("mail.myDomain.com","[email protected]","password");
st.sendMessage(msg, msg.getAllRecipients());

System.out.println("ServerResponse : " + st.getLastServerResponse());

It gives output for both valid and invalid email_address :- 250 OK id=1TbWgN-0007oY-8r

Please help me to resolve the problem. Thanks in advance.

Answer

Deepu picture Deepu · Nov 26, 2012

Thank you all for your responses.

I am able to solve my problem through MX Record checking .

I used this Link to resolve the problem. May this also be useful for someone.

Hashtable env = new Hashtable();
env.put("java.naming.factory.initial",
             "com.sun.jndi.dns.DnsContextFactory");
DirContext ictx = new InitialDirContext( env );
Attributes attrs = ictx.getAttributes
                       ( hostName, new String[] { "MX" });
Attribute attr = attrs.get( "MX" );
if (( attr == null ) || ( attr.size() == 0 )) {
   attrs = ictx.getAttributes( hostName, new String[] { "A" });
   attr = attrs.get( "A" );
   if( attr == null )
         throw new NamingException
                  ( "No match for name '" + hostName + "'" );
}

Thank you.