国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Java > 正文

如何準確判斷郵件地址是否存在

2019-11-26 15:04:37
字體:
來源:轉載
供稿:網友

我總結了幾種郵件出現重發、漏發的解釋:1.網絡;2.防火墻;3.服務器的自我保護,比如防止大批量發送時掛掉或者垃圾郵件,我覺得第三種解釋靠譜一些,對于遇到的這些問題在下面的文章中給出了補救措施。

公司郵箱目前使用的是Zimbra,該郵件服務器目前不甚穩定,經常出現重發、漏發問題。經測試,每100封郵件僅可成功發送98封左右,以下是測試數據:
測試用例1:100封,總用時約:16min;實收97封,失敗3次,3次錯誤信息均為:javax.mail.MessagingException: Could not connect to SMTP host
測試用例2:100封,總用時約:16min;實收100封,失敗2次,錯誤同上。加失敗重發機制,失敗后等待10s重發,最多重發3次;
測試用例3:每發一封,停留10s,總用時32min;實收100封,失敗1次,錯誤同上;重發機制同用例2.
關于MessagingException的問題,可以參考:
javax.mail.MessagingException: Could not connect to SMTP host
  針對這種問題,我增加了郵件重發,

if(sendHtmlMail_(mail)){    return true;    } else{    int i = 0;    //包含群組郵件,失敗不重發    boolean isNeedRe = isNeedRe(mail);    while(!sendHtmlMail_(mail) && isNeedRe && i < 10){    try {    i++;    Thread.sleep(1000*60);    } catch (InterruptedException e) {    LOGGER.error("resend mail error", e);    }    }    return true;    }

  但這種機制又產生了新的問題,因郵件服務器不穩定導致在僅發送一次的情況下也會向郵件收件人發送郵件,且同一封郵件的收件人(包括抄送、密送)可能部分收到郵件、部分收不到郵件。
  針對以上的問題,我們將重發機制去除,僅針對不合法郵件(即服務器上不存在的郵件地址)進行剔除,剔除后再進行發送。而對其他原因導致的郵件發送失敗不做重發(該問題將通過郵件服務器運維部門向廠商反映)。
   下面是判斷郵件是否合法的邏輯:
1.SMTP是工作在兩種情況下:一是電子郵件從客戶機傳輸到服務器;二是從某一個服務器傳輸到另一個服務器 
2.SMTP是個請求/響應協議,命令和響應都是基于ASCII文本,并以CR和LF符結束。響應包括一個表示返回狀態的三位數字代碼 
3.SMTP在TCP協議25號端口監聽連接請求 
4.連接和發送過程 
SMTP協議說復雜也不復雜,說簡單如果你懂得Socket。不過現在只是我們利用的就是第一條中說的,從客戶機傳輸到服務器,當我們向一臺服務器發送郵件時,郵件服務器會首先驗證郵件發送地址是否真的存在于本服務器上。 
5 操作的步驟如下: 
連接服務器的25端口(如果沒有郵件服務,連了也是白連) 
發送helo問候 
發送mail from命令,如果返回250表示正確可以,連接本服務器,否則則表示服務器需要發送人驗證。 
發送rcpt to命令,如果返回250表示則Email存在 
發送quit命令,退出連接 
基于上面這個邏輯,我們封裝郵件服務器形成Socket,發送命令,根據返回值來判斷郵件地址是否合法:
具體代碼如下:

import java.io.*;import java.net.*;import java.util.*;import javax.naming.*;import javax.naming.directory.*; public class SMTPMXLookup {  private static int hear( BufferedReader in ) throws IOException {   String line = null;   int res = 0;    while ( (line = in.readLine()) != null ) {     String pfx = line.substring( 0, 3 );     try {      res = Integer.parseInt( pfx );     }     catch (Exception ex) {      res = -1;     }     if ( line.charAt( 3 ) != '-' ) break;   }    return res;   }   private static void say( BufferedWriter wr, String text )   throws IOException {   wr.write( text + "/r/n" );   wr.flush();    return;   }   private static ArrayList getMX( String hostName )     throws NamingException {   // Perform a DNS lookup for MX records in the domain   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 we don't have an MX record, try the machine itself   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 + "'" );   }     // Huzzah! we have machines to try. Return them as an array list   // NOTE: We SHOULD take the preference into account to be absolutely   //  correct. This is left as an exercise for anyone who cares.   ArrayList res = new ArrayList();   NamingEnumeration en = attr.getAll();    while ( en.hasMore() ) {    String mailhost;    String x = (String) en.next();    String f[] = x.split( " " );    // THE fix *************    if (f.length == 1)      mailhost = f[0];    else if ( f[1].endsWith( "." ) )      mailhost = f[1].substring( 0, (f[1].length() - 1));    else      mailhost = f[1];    // THE fix *************          res.add( mailhost );   }   return res;   }   public static boolean isAddressValid( String address ) {   // Find the separator for the domain name   int pos = address.indexOf( '@' );    // If the address does not contain an '@', it's not valid   if ( pos == -1 ) return false;    // Isolate the domain/machine name and get a list of mail exchangers   String domain = address.substring( ++pos );   ArrayList mxList = null;   try {    mxList = getMX( domain );   }   catch (NamingException ex) {    return false;   }    // Just because we can send mail to the domain, doesn't mean that the   // address is valid, but if we can't, it's a sure sign that it isn't   if ( mxList.size() == 0 ) return false;    // Now, do the SMTP validation, try each mail exchanger until we get   // a positive acceptance. It *MAY* be possible for one MX to allow   // a message [store and forwarder for example] and another [like   // the actual mail server] to reject it. This is why we REALLY ought   // to take the preference into account.   for ( int mx = 0 ; mx < mxList.size() ; mx++ ) {     boolean valid = false;     try {       int res;       //       Socket skt = new Socket( (String) mxList.get( mx ), 25 );       BufferedReader rdr = new BufferedReader        ( new InputStreamReader( skt.getInputStream() ) );       BufferedWriter wtr = new BufferedWriter        ( new OutputStreamWriter( skt.getOutputStream() ) );        res = hear( rdr );       if ( res != 220 ) throw new Exception( "Invalid header" );       say( wtr, "EHLO rgagnon.com" );        res = hear( rdr );       if ( res != 250 ) throw new Exception( "Not ESMTP" );        // validate the sender address              say( wtr, "MAIL FROM: <tim@orbaker.com>" );       res = hear( rdr );       if ( res != 250 ) throw new Exception( "Sender rejected" );        say( wtr, "RCPT TO: <" + address + ">" );       res = hear( rdr );        // be polite       say( wtr, "RSET" ); hear( rdr );       say( wtr, "QUIT" ); hear( rdr );       if ( res != 250 )        throw new Exception( "Address is not valid!" );        valid = true;       rdr.close();       wtr.close();       skt.close();     }     catch (Exception ex) {      // Do nothing but try next host      ex.printStackTrace();     }     finally {      if ( valid ) return true;     }   }   return false;   }   public static void main( String args[] ) {   String testData[] = {     "real@rgagnon.com",     "you@acquisto.net",     "fail.me@nowhere.spam", // Invalid domain name     "arkham@bigmeanogre.net", // Invalid address     "nosuchaddress@yahoo.com" // Failure of this method     };    for ( int ctr = 0 ; ctr < testData.length ; ctr++ ) {    System.out.println( testData[ ctr ] + " is valid? " +       isAddressValid( testData[ ctr ] ) );   }   return;   }}

以上是判斷郵件地址是否合法的邏輯,如果郵件地址不合法,則將郵件地址從收件人列表中剔除。

private static String[] removeInvalidateAddress(String[] addresses, String mailFrom)   {       ArrayList<String> validateAddresses = new ArrayList<String>();     String normalAddress = null;     int code;           SMTPTransport smptTrans = null;     if(StringUtils.isEmpty(mailFrom) || null == addresses)     {       return new String[0];     }     String sendCmd = "MAIL FROM:" + normalizeAddress(mailFrom);     try     {     smptTrans = (SMTPTransport)sendSession.getTransport("smtp");     smptTrans.connect();     code = smptTrans.simpleCommand(sendCmd);     if(code != 250 && code != 251)     {       logger.error("send from invalidate" + mailFrom);     }     else     {       for(String address : addresses)       {         normalAddress = normalizeAddress(address);         String cmd = "RCPT TO:" + normalAddress;     code = smptTrans.simpleCommand(cmd);     if(code == 250 || code == 251)     {       validateAddresses.add(address);     }       }     }     }     catch(MessagingException e)     {       logger.error("Validate mail address error. send from " + mailFrom, e);     }           String[] result = validateAddresses.toArray(new String[validateAddresses.size()]);     return result;   }       private static String normalizeAddress(String addr)    {     if ((!addr.startsWith("<")) && (!addr.endsWith(">")))       return "<" + addr + ">";     else       return addr;   }

以上是本文的全部內容,希望大家能夠理解,對大家有所幫助。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 翁牛特旗| 安顺市| 永安市| 高邑县| 中卫市| 房山区| 泸溪县| 通辽市| 永州市| 秦皇岛市| 海兴县| 东兰县| 枣强县| 伊川县| 南漳县| 轮台县| 丰镇市| 古浪县| 循化| 阜新市| 莱西市| 云梦县| 鄂温| 上犹县| 阿拉善左旗| 鄯善县| 肇州县| 大英县| 抚宁县| 富川| 密山市| 罗定市| 格尔木市| 米林县| 肃南| 陇南市| 甘泉县| 阜宁县| 灌阳县| 青龙| 浪卡子县|