下面列出了怎么用javax.mail.AuthenticationFailedException的API类实例代码及写法,或者点击链接到github查看源代码。
private void openConnection(){
try{
Properties props = System.getProperties();
props.put( "mail.imap.partialfetch", "false" );
Session session = Session.getInstance(props, null);
mailStore = session.getStore( getData("service").getString().toLowerCase() );
mailStore.connect( getData("server").getString(), getData("username").getString(), getData("password").getString() );
setData( "succeeded", cfBooleanData.TRUE );
}catch(AuthenticationFailedException A){
setData( "errortext", new cfStringData( A.getMessage() ) );
}catch(MessagingException M){
setData( "errortext", new cfStringData( M.getMessage() ) );
}catch(SecurityException SE){
setData("errortext", new cfStringData("CFIMAP is not supported if SocketPermission is not enabled for the IMAP server. (" + SE.getMessage() + ")"));
}catch(Exception E){
setData( "errortext", new cfStringData( E.getMessage() ) );
}
}
@Test
public void testAuth() throws Throwable {
assertEquals(0, greenMail.getReceivedMessages().length);
String subject = GreenMailUtil.random();
String body = GreenMailUtil.random();
final MimeMessage message = GreenMailUtil.createTextEmail("[email protected]", "[email protected]",
subject, body, greenMail.getSmtp().getServerSetup());
Transport.send(message);
try {
Transport.send(message, "foo", "bar");
} catch (AuthenticationFailedException ex) {
assertTrue(ex.getMessage().contains(AuthCommand.AUTH_CREDENTIALS_INVALID));
}
greenMail.setUser("foo", "bar");
Transport.send(message, "foo", "bar");
greenMail.waitForIncomingEmail(1500, 3);
MimeMessage[] emails = greenMail.getReceivedMessages();
assertEquals(2, emails.length);
for (MimeMessage receivedMsg : emails) {
assertEquals(subject, receivedMsg.getSubject());
assertEquals(body, GreenMailUtil.getBody(receivedMsg).trim());
}
}
private void showError(Throwable ex) {
Log.e(ex);
pbOAuth.setVisibility(View.GONE);
if (ex instanceof IllegalArgumentException)
tvError.setText(ex.getMessage());
else
tvError.setText(Log.formatThrowable(ex));
grpError.setVisibility(View.VISIBLE);
if ("gmail".equals(id))
tvGmailDraftsHint.setVisibility(View.VISIBLE);
if ("office365".equals(id) &&
ex instanceof AuthenticationFailedException)
tvOfficeAuthHint.setVisibility(View.VISIBLE);
btnOAuth.setEnabled(true);
pbOAuth.setVisibility(View.GONE);
new Handler().post(new Runnable() {
@Override
public void run() {
scroll.smoothScrollTo(0, tvError.getBottom());
}
});
}
/**
* handles the sendFailedException
* <p>
* creates a MessageSendStatus which contains a translateable info or error message, and the knowledge if the user can proceed with its action.
*
* @param e
* @throws OLATRuntimeException return MessageSendStatus
*/
private MessageSendStatus handleSendFailedException(final SendFailedException e) {
// get wrapped excpetion
MessageSendStatus messageSendStatus = null;
final MessagingException me = (MessagingException) e.getNextException();
if (me instanceof AuthenticationFailedException) {
messageSendStatus = createAuthenticationFailedMessageSendStatus();
return messageSendStatus;
}
final String message = me.getMessage();
if (message.startsWith("553")) {
messageSendStatus = createInvalidDomainMessageSendStatus();
} else if (message.startsWith("Invalid Addresses")) {
messageSendStatus = createInvalidAddressesMessageSendStatus(e.getInvalidAddresses());
} else if (message.startsWith("503 5.0.0")) {
messageSendStatus = createNoRecipientMessageSendStatus();
} else if (message.startsWith("Unknown SMTP host")) {
messageSendStatus = createUnknownSMTPHost();
} else if (message.startsWith("Could not connect to SMTP host")) {
messageSendStatus = createCouldNotConnectToSmtpHostMessageSendStatus();
} else {
List<ContactList> emailToContactLists = getTheToContactLists();
String exceptionMessage = "";
for (ContactList contactList : emailToContactLists) {
exceptionMessage += contactList.toString();
}
throw new OLATRuntimeException(ContactUIModel.class, exceptionMessage, me);
}
return messageSendStatus;
}
@Test
public void shouldFailWithSendFailedExceptionWithAnAuthenticationFailedException(){
//setup
ExceptionHandlingMailSendingTemplate doSendWithSendFailedException = new ExceptionHandlingMailSendingTemplate() {
@Override
protected boolean doSend(Emailer emailer) throws AddressException, SendFailedException, MessagingException {
assertNotNull("emailer was constructed", emailer);
MessagingException firstInnerException = new AuthenticationFailedException("<some authentication failed message from the mailsystem>");
throw new SendFailedException(BY_OLAT_UNHANDLED_TEXT, firstInnerException);
}
@Override
protected MailTemplate getMailTemplate() {
return emptyMailTemplate;
};
@Override
protected List<ContactList> getTheToContactLists() {
return theContactLists;
}
@Override
protected Identity getFromIdentity() {
return theFromIdentity;
}
};
//exercise
MessageSendStatus sendStatus = doSendWithSendFailedException.send();
//verify
assertEquals(MessageSendStatusCode.SMTP_AUTHENTICATION_FAILED, sendStatus.getStatusCode());
verifyStatusCodeIndicateSendFailedOnly(sendStatus);
verifySendStatusIsError(sendStatus);
assertTrue(sendStatus.canProceedWithWorkflow());
}
private void handleException(MessagingException e){
if (e instanceof AuthenticationFailedException) {
lastError = ErrorTyp.AUTHENTICATION;
} else if (e.getNextException() instanceof UnknownHostException
|| e.getNextException() instanceof ConnectException) {
lastError = ErrorTyp.CONNECTION;
} else if (e instanceof AddressException) {
lastError = ErrorTyp.ADDRESS;
}
}
static String formatThrowable(Throwable ex, String separator, boolean sanitize) {
if (sanitize) {
if (ex instanceof MessageRemovedException)
return null;
if (ex instanceof AuthenticationFailedException &&
ex.getCause() instanceof SocketException)
return null;
if (ex instanceof MessagingException &&
("connection failure".equals(ex.getMessage()) ||
"failed to create new store connection".equals(ex.getMessage())))
return null;
if (ex instanceof MessagingException &&
ex.getCause() instanceof ConnectionException &&
ex.getCause().getMessage() != null &&
(ex.getCause().getMessage().contains("Read error") ||
ex.getCause().getMessage().contains("Write error") ||
ex.getCause().getMessage().contains("Unexpected end of ZLIB input stream") ||
ex.getCause().getMessage().contains("Socket is closed")))
return null;
// javax.mail.MessagingException: AU3 BAD User is authenticated but not connected.;
// nested exception is:
// com.sun.mail.iap.BadCommandException: AU3 BAD User is authenticated but not connected.
// javax.mail.MessagingException: AU3 BAD User is authenticated but not connected.;
// nested exception is:
// com.sun.mail.iap.BadCommandException: AU3 BAD User is authenticated but not connected.
// at com.sun.mail.imap.IMAPFolder.logoutAndThrow(SourceFile:1156)
// at com.sun.mail.imap.IMAPFolder.open(SourceFile:1063)
// at com.sun.mail.imap.IMAPFolder.open(SourceFile:977)
// at eu.faircode.email.ServiceSynchronize.monitorAccount(SourceFile:890)
// at eu.faircode.email.ServiceSynchronize.access$1500(SourceFile:85)
// at eu.faircode.email.ServiceSynchronize$7$1.run(SourceFile:627)
// at java.lang.Thread.run(Thread.java:764)
// Caused by: com.sun.mail.iap.BadCommandException: AU3 BAD User is authenticated but not connected.
// at com.sun.mail.iap.Protocol.handleResult(SourceFile:415)
// at com.sun.mail.imap.protocol.IMAPProtocol.select(SourceFile:1230)
// at com.sun.mail.imap.IMAPFolder.open(SourceFile:1034)
if (ex instanceof MessagingException &&
ex.getCause() instanceof BadCommandException &&
ex.getCause().getMessage() != null &&
ex.getCause().getMessage().contains("User is authenticated but not connected"))
return null;
if (ex instanceof IOException &&
ex.getCause() instanceof MessageRemovedException)
return null;
if (ex instanceof ConnectionException)
return null;
if (ex instanceof StoreClosedException ||
ex instanceof FolderClosedException || ex instanceof FolderClosedIOException)
return null;
if (ex instanceof IllegalStateException &&
("Not connected".equals(ex.getMessage()) ||
"This operation is not allowed on a closed folder".equals(ex.getMessage())))
return null;
}
StringBuilder sb = new StringBuilder();
if (BuildConfig.DEBUG)
sb.append(ex.toString());
else
sb.append(ex.getMessage() == null ? ex.getClass().getName() : ex.getMessage());
Throwable cause = ex.getCause();
while (cause != null) {
if (BuildConfig.DEBUG)
sb.append(separator).append(cause.toString());
else
sb.append(separator).append(cause.getMessage() == null ? cause.getClass().getName() : cause.getMessage());
cause = cause.getCause();
}
return sb.toString();
}
/**
* 消息发送接口实现
*/
@Override
@Transactional
public void send() {
LogUtil.info("===============消息发扫描开始=================");
//List<TSSmsEntity> smsSendList = findHql("from TSSmsEntity e where e.esStatus = ? or e.esStatus = ? ", Constants.SMS_SEND_STATUS_1,Constants.SMS_SEND_STATUS_3);
List<TSSmsEntity> smsSendList = findHql("from TSSmsEntity e where e.esStatus = ?", Constants.SMS_SEND_STATUS_1);
if(smsSendList==null || smsSendList.size()==0){
return;
}
PropertiesUtil util = new PropertiesUtil("sysConfig.properties");
for (TSSmsEntity tsSmsEntity : smsSendList) {
String remark = "";
if(Constants.SMS_SEND_TYPE_2.equals(tsSmsEntity.getEsType())){
//邮件
try {
MailUtil.sendEmail(util.readProperty("mail.smtpHost"), tsSmsEntity.getEsReceiver(),tsSmsEntity.getEsTitle(),
tsSmsEntity.getEsContent(), util.readProperty("mail.sender"),
util.readProperty("mail.user"), util.readProperty("mail.pwd"));
tsSmsEntity.setEsStatus(Constants.SMS_SEND_STATUS_2);
tsSmsEntity.setEsSendtime(new Date());
remark = "发送成功";
tsSmsEntity.setRemark(remark);
updateEntitie(tsSmsEntity);
} catch (Exception e) {
//tsSmsEntity.setEsStatus(Constants.SMS_SEND_STATUS_3);
if (e instanceof AuthenticationFailedException){
remark = "认证失败错误的用户名或者密码";
}else if (e instanceof SMTPAddressFailedException){
remark = "接受邮箱格式不对";
}else if (e instanceof ConnectException){
remark = "邮件服务器连接失败";
}else{
remark = e.getMessage();
}
//System.out.println(remark);
//e.printStackTrace();
tsSmsEntity.setEsStatus(Constants.SMS_SEND_STATUS_3);
tsSmsEntity.setEsSendtime(new Date());
tsSmsEntity.setRemark(remark);
updateEntitie(tsSmsEntity);
}
}
if(Constants.SMS_SEND_TYPE_1.equals(tsSmsEntity.getEsType())){
//短信
String r = CMPPSenderUtil.sendMsg(tsSmsEntity.getEsReceiver(), tsSmsEntity.getEsContent());
if ("0".equals(r)){
tsSmsEntity.setEsStatus(Constants.SMS_SEND_STATUS_2);
}else {
tsSmsEntity.setEsStatus(Constants.SMS_SEND_STATUS_3);
}
}
//更新发送状态
tsSmsEntity.setRemark(remark);
tsSmsEntity.setEsSendtime(new Date());
updateEntitie(tsSmsEntity);
}
LogUtil.info("===============消息发扫描结束=================");
}