java发送邮件错误:550 Mailbox not found or access denied

1、首先,遇到这种问题,是标准码,所以我们查询邮箱协议,发现550错误为:

    收件箱地址不对(我相信大多数不是这样) 收件箱拒收我们; 那么遇到这种拒收怎么办? 2、我们根据返回错误: 发现根源异常Exception:后端的SMTPAddressFailedException,所以可以写代码来判断,然后根据判断来进行相应的重新发送,先说判断:
/** 通过遍历MailSendException的异常,来判断是否符合我们的检测条件,我们可以自定义predicate */
	public static final boolean checkEmailExceptionCode(Exception emailException, Predicate<Exception> predicate) {
          
   
		if(emailException instanceof MailSendException) {
          
   
			MailSendException mse = (MailSendException) emailException;
			if(mse.getMessageExceptions() != null) {
          
   
				for (Exception me : mse.getMessageExceptions()) {
          
   
					if(predicate.test(me)) {
          
   
						// 只有为true才直接返回
						return true;
					}
				}
			}
		}
		return false;
	}

	/** 检测是否是收件人错误,条件:
	 * 1、SMTPAddressFailedException
	 * 2、rc=550
	 *  */
	static final Predicate<Exception> recieverInvalidPredicate = (me) -> {
          
   
		while(me != null) {
          
   
			if(me instanceof SMTPAddressFailedException) {
          
   
				SMTPAddressFailedException safe = (SMTPAddressFailedException) me;
				if(safe.getReturnCode() == 550) {
          
   
					// 这是收件箱地址不对或者收件箱服务器拒收
					return true;
				}
			} else {
          
   
				if(me instanceof SendFailedException) {
          
   
					SendFailedException sfe = (SendFailedException) me;
					me = sfe.getNextException();
				}
			}
		}
		return false;
	};
	
	/** 检测是否是收件人错误 */
	public static final boolean checkEmailRecieverInvalid(Exception emailException) {
          
   
		return checkEmailExceptionCode(emailException, recieverInvalidPredicate);
	}

到时候直接调用checkEmailRecieverInvalid(Exception e)就可以了; 如果要扩展新的错误判断类型,可以增加predicate,然后再封装一个暴露出去的函数方法,如checkEmailRecieverInvalid; 3、既然判断了,我们就可以根据这个判断来解决了 在上图的发送代码中,我们将收件人设置成发件人,也就是自己给自己发送邮件,可以测试发送邮箱的参数的有效性;

后记: 为了避免发送邮件被拒收,我们可以增加邮件内容的丰富性,也就是每次的内容要有差异性,可以采用:

    插入随机片段 无意义随机码 等方式;
经验分享 程序员 微信小程序 职场和发展