问题:使用javaMail发送邮件时(群发),出现异常,提示信息为:

org.springframework.mail.MailSendException: Failed messages: javax.mail.SendFailedException: Invalid Addresses;
  nested exception is:
    com.sun.mail.smtp.SMTPAddressFailedException: 550 Mailbox not found or access denied
;
  nested exception is:
    com.sun.mail.smtp.SMTPAddressFailedException: 550 Mailbox not found or access denied

原因:群发的地址中,有一个或多个是无效的地址。可是,错误提示并没有列出这些错误的地址来,靠肉眼找出来很麻烦。

解决:捕捉到异常时,把无效的地址打印出来:

        try {
			sender.send(message);
			logger.debug("简单邮件已经发送。");
		}catch (MailSendException me){
			detectInvalidAddress(me);
		}
	private void detectInvalidAddress(MailSendException me) {
		Exception[] messageExceptions = me.getMessageExceptions();
		if (messageExceptions.length > 0) {
			Exception messageException = messageExceptions[0];
			if (messageException instanceof SendFailedException) {
				SendFailedException sfe = (SendFailedException) messageException;
				Address[] invalidAddresses = sfe.getInvalidAddresses();
				if(invalidAddresses != null) {
					StringBuilder addressStr = new StringBuilder();
					for (Address address : invalidAddresses) {
						addressStr.append(address.toString()).append("; ");
					}

					logger.error("发送邮件时发生异常!可能有无效的邮箱:{}", addressStr);
					return;
				}
			}
		}

		logger.error("发送邮件时发生异常!", me);
	}

 

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐