/** * API to validate email configuration. * * @param emailConfigDTO {@link EmailConfigurationDTO} Email Configuration to be verified. * @return {@link Boolean} returns true if valid email configuration otherwise false. * @throws {@link GWTException} */ @Override public Boolean validateEmailConfig(final EmailConfigurationDTO emailConfigDTO) throws GWTException { LOGGER.info("Entering method validateEmailConfig."); EmailConfigurationData emailConfigData = createEmailConfigData(emailConfigDTO); boolean isValid = false; try { isValid = EmailUtil.testEmailConfiguration(emailConfigData); if (!isValid) { throw new GWTException("Unable to connect to email configuration. See server logs for details."); } } catch (AuthenticationFailedException authExcep) { throw new GWTException(authExcep.getMessage()); } catch (MessagingException messageException) { throw new GWTException(messageException.getMessage()); } LOGGER.info("Exiting method validateEmailConfig."); return isValid; }
/** * API to test the email configuration. * * @param emailConfigData {@link EmailConfigurationData} * @return true or false based on the connection made successfully with the email setting passed * @throws MessagingException {@link MessagingException} * @throws AuthenticationFailedException {@link AuthenticationFailedException} */ public static boolean testEmailConfiguration(final EmailConfigurationData emailConfigData) throws MessagingException, AuthenticationFailedException { LOGGER.info("Enter method testEmailConfiguration."); boolean isBValidConfig = true; Store store = null; if (emailConfigData != null) { String serverType = emailConfigData.getServerType(); LOGGER.debug("Server type :: " + serverType); if (emailConfigData.getIsSSL()) { if (IUtilCommonConstants.POP3_CONFIG.equalsIgnoreCase(serverType)) { store = connectWithPOP3SSL(emailConfigData); } else if (IUtilCommonConstants.IMAP_CONFIG.equalsIgnoreCase(serverType)) { store = connectWithIMAPSSL(emailConfigData); } else { LOGGER.error("Error in Server Type Configuration, only imap/pop3 is allowed."); throw new MessagingException("Error in Server Type Configuration, only imap/pop3 is allowed."); } } else { store = connectWithNonSSL(emailConfigData); } } if (store == null || !store.isConnected()) { LOGGER.error("Not able to establish connection. Please check settings."); isBValidConfig = false; } LOGGER.info("Exiting method testEmailConfiguration."); return isBValidConfig; }
/** * API to connect to the email configuration with POP3 server type. * * @param emailConfigData {@link EmailConfigurationData} * @return * @throws MessagingException {@link MessagingException} * @throws AuthenticationFailedException {@link AuthenticationFailedException} */ public static Store connectWithPOP3SSL(final EmailConfigurationData emailConfigData) throws MessagingException, AuthenticationFailedException { LOGGER.info("Entering method connectWithPOP3SSL..."); Properties pop3Props = new Properties(); pop3Props.setProperty("mail.pop3.socketFactory.class", IUtilCommonConstants.SSL_FACTORY); pop3Props.setProperty("mail.pop3.socketFactory.fallback", "false"); Integer portNumber = emailConfigData.getPortNumber(); LOGGER.debug("Port Number :: " + portNumber); if (portNumber == null) { LOGGER.error("Could not find port number. Trying with default value of 995"); throw new MessagingException("Could not connect to port number " + portNumber + ". Try connecting with defualt port number " + IUtilCommonConstants.DEFAULT_PORT_NUMBER_POP3 + " for pop3 and " + IUtilCommonConstants.DEFAULT_PORT_NUMBER_IMAP + " for IMAP "); } URLName url = new URLName(emailConfigData.getServerType(), emailConfigData.getServerName(), portNumber, "", emailConfigData .getUserName(), emailConfigData.getPassword()); Session session = Session.getInstance(pop3Props, null); Store store = new POP3SSLStore(session, url); store.connect(); LOGGER.info("Exiting method connectWithPOP3SSL..."); return store; }
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 testCreateMessageStoreWithEnableTLSInputTrueExceptionAndEnableSSLInputTrue() throws Exception { PowerMockito.whenNew(Properties.class).withNoArguments().thenReturn(propertiesMock); PowerMockito.whenNew(SimpleAuthenticator.class).withArguments(anyString(), anyString()).thenReturn(authenticatorMock); doNothing().when(getMailMessageSpy).addSSLSettings(anyBoolean(), anyString(), anyString(), anyString(), anyString()); doReturn(storeMock).when(getMailMessageSpy).configureStoreWithTLS(propertiesMock, authenticatorMock); doThrow(AuthenticationFailedException.class).when(storeMock).connect(HOST, USERNAME, PASSWORD); doReturn(storeMock).when(getMailMessageSpy).configureStoreWithSSL(propertiesMock, authenticatorMock); doNothing().when(storeMock).connect(); addRequiredInputs(); inputs.setEnableSSL(STR_TRUE); inputs.setEnableTLS(STR_TRUE); getMailMessageSpy.processInputs(inputs); assertEquals(storeMock, getMailMessageSpy.createMessageStore()); PowerMockito.verifyNew(Properties.class).withNoArguments(); PowerMockito.verifyNew(SimpleAuthenticator.class).withArguments(anyString(), anyString()); verify(getMailMessageSpy).addSSLSettings(anyBoolean(), anyString(), anyString(), anyString(), anyString()); verify(getMailMessageSpy).configureStoreWithTLS(propertiesMock, authenticatorMock); verify(getMailMessageSpy).configureStoreWithSSL(propertiesMock, authenticatorMock); }
/** * Connects to imap, returns a store. * * @return the store where, where you can read the emails * @throws NoSuchProviderException * @throws MessagingException * @throws AuthenticationFailedException */ private synchronized Store getStore() throws NoSuchProviderException, MessagingException, AuthenticationFailedException { Properties props = System.getProperties(); this.setProperties(props); Session session = Session.getDefaultInstance(props, null); Store store; if (this.account.isSsl()) { store = session.getStore("imaps"); } else { store = session.getStore("imap"); } Log.d("rgai3", "connecting with account: " + account); store.connect(account.getImapAddress(), account.getEmail(), account.getPassword()); return store; }
/** * 发送126邮箱 * * @param toMail * @param subject * @param text * @return */ @SuppressWarnings("rawtypes") public boolean send126Mail(String toMail, String subject, String text) throws AuthenticationFailedException,MailException{ Email email = Email.create().from(USER_126).to(toMail) .subject(subject).addText(text); SmtpServer smtpServer = SmtpServer.create("smtp.126.com") .authenticateWith(USER_126, PASSWORD_126); SendMailSession session = smtpServer.createSession(); session.open(); session.sendMail(email); session.close(); return true; }
/** * 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()); }
@Override public MessageListResult getMessageList(int offset, int limit, TreeSet<MessageListElement> loadedMessages, boolean isNewMessageArrivedRequest) throws CertPathValidatorException, SSLHandshakeException, ConnectException, NoSuchProviderException, UnknownHostException, IOException, MessagingException, AuthenticationFailedException { return getMessageList(offset, limit, loadedMessages, 20, isNewMessageArrivedRequest); }
private void handleException(MessagingException e){ if (e instanceof AuthenticationFailedException) { lastError = ErrorTyp.AUTHENTICATION; } else if (e.getNextException() instanceof UnknownHostException) { lastError = ErrorTyp.CONNECTION; } else if (e instanceof AddressException) { lastError = ErrorTyp.ADDRESS; } }
/** * API to connect to a non ssl email config. Returns the {@link Store} object which provides many common methods for naming stores, * connecting to stores, and listening to connection events. * * * @param emailConfigData {@link EmailConfigurationData} * @return * @throws MessagingException {@link MessagingException} * @throws AuthenticationFailedException {@link AuthenticationFailedException} */ public static Store connectWithNonSSL(final EmailConfigurationData emailConfigData) throws MessagingException, AuthenticationFailedException { LOGGER.info("Entering method connectWithNonSSL..."); Session session = Session.getDefaultInstance(System.getProperties(), null); Store store = session.getStore(emailConfigData.getServerType()); store.connect(emailConfigData.getServerName(), emailConfigData.getUserName(), emailConfigData.getPassword()); LOGGER.info("Exiting method connectWithNonSSL..."); return store; }
/** * Returns the list of messages. * * @param offset the offset of the queried messages * @param limit the limit of queried messages * @param loadedMessages the list of message that already loaded * @return List of MessageListElement objects, the list of messages * @throws CertPathValidatorException * @throws SSLHandshakeException * @throws ConnectException * @throws NoSuchProviderException * @throws UnknownHostException * @throws IOException * @throws MessagingException * @throws AuthenticationFailedException */ public MessageListResult getMessageList(int offset, int limit, TreeSet<MessageListElement> loadedMessages, boolean isNewMessageArrivedRequest) throws CertPathValidatorException, SSLHandshakeException, ConnectException, NoSuchProviderException, UnknownHostException, IOException, MessagingException, AuthenticationFailedException;
/** * Returns the list of messages. * * @param offset the offset of the queried messages * @param limit the limit of queried messages * @param loadedMessages * @param snippetMaxLength the max length of the snippet * @return List of MessageListElement objects, the list of messages * @throws CertPathValidatorException * @throws SSLHandshakeException * @throws ConnectException * @throws NoSuchProviderException * @throws UnknownHostException * @throws IOException * @throws MessagingException * @throws AuthenticationFailedException */ public MessageListResult getMessageList(int offset, int limit, TreeSet<MessageListElement> loadedMessages, int snippetMaxLength, boolean isNewMessageArrivedRequest) throws CertPathValidatorException, SSLHandshakeException, ConnectException, NoSuchProviderException, UnknownHostException, IOException, MessagingException, AuthenticationFailedException;