/**
* 根据邮件地址,获得邮件服务器
* @param mail
* @return
* lupingui
* 2009-4-17
*/
public static String getSmtpHost(String mail){
//获得邮件Domain
int atMarkPosition = mail.indexOf("@");
if (atMarkPosition < 1){
return null;
}
String mailDomain = mail.substring(atMarkPosition + 1);
boolean isMxSuccessful = false;
//查询邮件交换记录
Lookup lookup = null;
try {
lookup = new Lookup(mailDomain, Type.MX);
lookup.run();
if(lookup.getResult() == Lookup.SUCCESSFUL){
isMxSuccessful = true;
}else{
lookup = new Lookup(mailDomain);
lookup.run();
if(lookup.getResult() != Lookup.SUCCESSFUL){
return null;
}
}
} catch (TextParseException ex) {
ex.printStackTrace();
return null;
}
//得到服务器列表
Record[] answers = lookup.getAnswers();
String[] hostArray = new String[answers.length];
for (int i = 0; i < answers.length; i++) {
Record record = answers[i];
Name name = record.getAdditionalName();
if(!isMxSuccessful){
name = record.getName();
}
int labelCount = name.labels();
StringBuffer sbf = new StringBuffer();
for (int j = 0; j < labelCount; j++) {
String labelString = name.getLabelString(j);
if(!labelString.equals("")){
sbf.append(labelString).append(".");
}
}
if(sbf.length() > 0 && sbf.charAt(sbf.length()-1) == '.'){
sbf.deleteCharAt(sbf.length()-1);
}
hostArray[i] = sbf.toString();
}
//返回,如果有多个则随机返回一个。
if(hostArray.length == 1){
return hostArray[0];
}else{
Random random = new Random();
int index = random.nextInt(hostArray.length);
return hostArray[index];
}
}