6

Anybody knows how to get MX address (from for example gmail.com) in java using standard libraries? Or do I need to download external one?

I'm using netbeans if it can be helpful (if it provides something for this).

JasonMArcher
  • 14,195
  • 22
  • 56
  • 52
oneat
  • 10,778
  • 16
  • 52
  • 70
  • Does the solution need to be platform independent, and if not, which platform will it run on? – MrLore Dec 26 '12 at 15:43
  • You can look at this question : http://stackoverflow.com/questions/10261995/finding-smtp-host-and-port-knowing-the-e-mail-address-using-java-api – Guillaume Dec 26 '12 at 15:45

2 Answers2

15

I was also searching for standart lib for this in java. Unsuccessful.

Then I have used dnsjava.

private Record[] lookupMxRecords(final String domainPart) throw TextParseException
{
    final Lookup dnsLookup = new Lookup(domainPart, Type.MX);
    return dnsLookup.run();
}
Dolda2000
  • 25,216
  • 4
  • 51
  • 92
Walery Strauch
  • 6,792
  • 8
  • 50
  • 57
1

Main.java

import java.util.Enumeration;
import java.util.Hashtable;

import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;

public class Main {
    public static void main(String args[]) throws Exception {
        Hashtable<String, String> env = new Hashtable<String, String>();
        env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
        env.put("java.naming.provider.url", "dns://8.8.8.8/");
        DirContext ctx = new InitialDirContext(env);
        Attributes attrsl = ctx.getAttributes("google.com", new String[] {"MX"});
        Attribute attr = attrsl.get("MX");
        if (attr != null) {
            System.out.println("MX records:");
            for (Enumeration vals = attr.getAll(); vals.hasMoreElements();) {
                System.out.println(vals.nextElement());
            }
        }
    }
}

issues

$ javac Main.java && java Main
MX records:
20 alt1.aspmx.l.google.com.
50 alt4.aspmx.l.google.com.
10 aspmx.l.google.com.
40 alt3.aspmx.l.google.com.
30 alt2.aspmx.l.google.com.
Gerrit Griebel
  • 405
  • 3
  • 10