java 发送邮件时处理不可达的收件人
报错信息:
javax.mail.SendFailedException: Invalid Addresses; nested exception is: com.sun.mail.smtp.SMTPAddressFailedException: 550 5.7.1 Unable to relay for aerchi@gmail.com
两种改法:
第一种:排查收件人地址是否正确(我还是推荐这种改法,避免了负责人收不到邮件)
第二种:获取有效收件人(对于收件人没法指定要求这个还是不错的,保障部分负责人能收到邮件)
getInvalidAddresses( )获取无效且因此未发送到的地址数组
getValidSentAddresses()获取成功发送此消息的地址数组
getValidUnsentAddresses()获取一个地址数组有效但邮件未发送到该邮件
方法:
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: aerchi@gmail.com * 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(); } }
学习来源:https://blog.csdn.net/aerchi/article/details/41692913
https://www.cnblogs.com/yejg1212/archive/2013/06/01/3112702.html
https://www.it1352.com/992663.html
https://blog.csdn.net/xiaomage1314/article/details/72957119