由于某个模块用到程序运行完后,自动收集结果发送邮件给相关人等。假如邮件收件人里某个地址貌似出问题,会导致所有的收件人地址都发送不出去。
javax.mail.SendFailedException: Invalid Addresses;
nested exception is:
com.sun.mail.smtp.SMTPAddressFailedException: 550 5.7.1 Unable to relay for [email protected]
at com.sun.mail.smtp.SMTPTransport.rcptTo(SMTPTransport.java:1196)
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:584)
at javax.mail.Transport.send0(Transport.java:169)
at javax.mail.Transport.send(Transport.java:98)
at AtGroup.ServerBasicCheck.ServerCheck.sendMail(ServerCheck.java:1651)
at AtGroup.ServerBasicCheck.ServerCheck.callRun(ServerCheck.java:500)
at AtGroup.ServerBasicCheck.ServerCheck.main(ServerCheck.java:310)
Caused by: com.sun.mail.smtp.SMTPAddressFailedException: 550 5.7.1 Unable to relay for [email protected]
at com.sun.mail.smtp.SMTPTransport.rcptTo(SMTPTransport.java:1047)
... 6 more
这个是致使的错误呀,研究了半天。
改进代码如下:(跳过错误或不可达的收件人地址)
try{ Transport.send(msg); // Transport.sendMessage(msg); Out.println("the mail send successful First. "+Out.getNowDate()); }catch(UnsupportedEncodingException e) { e.printStackTrace(); }catch(SendFailedException se) { se.printStackTrace(); // Exception ex = me; // if (ex instanceof SendFailedException) {} Address[] unsend = se.getValidUnsentAddresses(); if(null!=unsend) { // Out.println(" ==valid Addresses"); String validAddress = ""; for(int i=0;i<unsend.length;i++){ validAddress += unsend[i] + ";"; // Out.println((i+1)+": " + unsend[i]); } validAddress = validAddress.substring(0,validAddress.length()-1); // Out.println("All: "+validAddress); // send the mail when mail address wrong. sendFailMail(new MimeMessage(mailSession), mailBody, mailFrom, validAddress); } }catch(MessagingException me) {me.printStackTrace();} } /** * email: [email protected] * site: www.aerchi.com * blog: http://blog.csdn.net/aerchi */ //send the mail when mail address wrong. public static void sendFailMail(Message msg, BodyPart mailBody, Address mailFrom, String mailTOAddress ) { try{ Out.println("...Send the mail second time."); msg.setSentDate(new Date()); msg.setFrom(mailFrom); String[] mailTOArray=null; mailTOArray=mailTOAddress.split(";"); InternetAddress[] mailTOAdd = null; mailTOAdd = new InternetAddress[mailTOArray.length]; for(int a=0;a<mailTOArray.length;a++) { // Out.println(mailTOArray[a]); mailTOAdd[a]= new InternetAddress(mailTOArray[a]); } msg.setRecipients(Message.RecipientType.TO, mailTOAdd); msg.setSubject(mailSubject); Multipart mailMulti = new MimeMultipart(); // mailBody.setContent(mainText, "text/html;charset=utf-8"); mailMulti.addBodyPart(mailBody); msg.setContent(mailMulti); Transport.send(msg); Out.println("...the mail send successful Second. "+Out.getNowDate()); }catch(MessagingException me) {me.printStackTrace();} }
最后,大功靠成。如有地址错误或不可到达(会自动跳过),保证能够对其它有效地址发送邮件,再也不用担心导致其它收件人不能收到邮件啦。
文章版权归作者[Aerchi]所 有,请勿采集,转载务必请注明作者及原文地址。
本文地址: http://blog.csdn.net/aerchi/article/details/41692913