Search in sources :

Example 1 with AuthenticationFailedException

use of javax.mail.AuthenticationFailedException in project adempiere by adempiere.

the class EMail method send.

/**
	 *	Send Mail direct
	 *	@return OK or error message
	 */
public String send() {
    log.info("(" + m_Host + ") " + m_from + " -> " + m_to);
    m_sentMsg = null;
    //
    if (!isValid(true)) {
        m_sentMsg = "Invalid Data";
        return m_sentMsg;
    }
    //	FR [ 402 ]
    Session session = null;
    try {
        session = getSession();
    } catch (SecurityException se) {
        log.log(Level.WARNING, "Auth=" + m_auth + " - " + se.toString());
        m_sentMsg = se.toString();
        return se.toString();
    } catch (Exception e) {
        log.log(Level.SEVERE, "Auth=" + m_auth, e);
        m_sentMsg = e.toString();
        return e.toString();
    }
    try {
        m_msg = new SMTPMessage(session);
        //	Addresses
        m_msg.setFrom(m_from);
        InternetAddress[] rec = getTos();
        if (rec.length == 1)
            m_msg.setRecipient(Message.RecipientType.TO, rec[0]);
        else
            m_msg.setRecipients(Message.RecipientType.TO, rec);
        rec = getCcs();
        if (rec != null && rec.length > 0)
            m_msg.setRecipients(Message.RecipientType.CC, rec);
        rec = getBccs();
        if (rec != null && rec.length > 0)
            m_msg.setRecipients(Message.RecipientType.BCC, rec);
        if (m_replyTo != null)
            m_msg.setReplyTo(new Address[] { m_replyTo });
        //
        m_msg.setSentDate(new java.util.Date());
        m_msg.setHeader("Comments", "AdempiereMail");
        //	SMTP specifics
        m_msg.setAllow8bitMIME(true);
        //	Send notification on Failure & Success - no way to set envid in Java yet
        //	Bounce only header
        m_msg.setReturnOption(SMTPMessage.RETURN_HDRS);
        //
        setContent();
        m_msg.saveChanges();
        log.fine("message =" + m_msg);
        //
        getTransport(session);
        Transport.send(m_msg);
        log.fine("Success - MessageID=" + m_msg.getMessageID());
    } catch (MessagingException me) {
        Exception ex = me;
        StringBuffer sb = new StringBuffer("(ME)");
        boolean printed = false;
        do {
            if (ex instanceof SendFailedException) {
                SendFailedException sfex = (SendFailedException) ex;
                Address[] invalid = sfex.getInvalidAddresses();
                if (!printed) {
                    if (invalid != null && invalid.length > 0) {
                        sb.append(" - Invalid:");
                        for (int i = 0; i < invalid.length; i++) sb.append(" ").append(invalid[i]);
                    }
                    Address[] validUnsent = sfex.getValidUnsentAddresses();
                    if (validUnsent != null && validUnsent.length > 0) {
                        sb.append(" - ValidUnsent:");
                        for (int i = 0; i < validUnsent.length; i++) sb.append(" ").append(validUnsent[i]);
                    }
                    Address[] validSent = sfex.getValidSentAddresses();
                    if (validSent != null && validSent.length > 0) {
                        sb.append(" - ValidSent:");
                        for (int i = 0; i < validSent.length; i++) sb.append(" ").append(validSent[i]);
                    }
                    printed = true;
                }
                if (sfex.getNextException() == null)
                    sb.append(" ").append(sfex.getLocalizedMessage());
            } else if (ex instanceof AuthenticationFailedException) {
                sb.append(" - Invalid Username/Password - " + m_auth);
            } else //	other MessagingException 
            {
                String msg = ex.getLocalizedMessage();
                if (msg == null)
                    sb.append(": ").append(ex.toString());
                else {
                    if (msg.indexOf("Could not connect to SMTP host:") != -1) {
                        int index = msg.indexOf('\n');
                        if (index != -1)
                            msg = msg.substring(0, index);
                        String cc = "??";
                        if (m_ctx != null)
                            cc = m_ctx.getProperty("#AD_Client_ID");
                        msg += " - AD_Client_ID=" + cc;
                    }
                    String className = ex.getClass().getName();
                    if (className.indexOf("MessagingException") != -1)
                        sb.append(": ").append(msg);
                    else
                        sb.append(" ").append(className).append(": ").append(msg);
                }
            }
            //	Next Exception
            if (ex instanceof MessagingException)
                ex = ((MessagingException) ex).getNextException();
            else
                ex = null;
        } while (//	error loop
        ex != null);
        //
        if (CLogMgt.isLevelFinest())
            log.log(Level.WARNING, sb.toString(), me);
        else
            log.log(Level.WARNING, sb.toString());
        m_sentMsg = sb.toString();
        return sb.toString();
    } catch (Exception e) {
        log.log(Level.SEVERE, "", e);
        m_sentMsg = e.getLocalizedMessage();
        return e.getLocalizedMessage();
    }
    //
    if (CLogMgt.isLevelFinest())
        dumpMessage();
    m_sentMsg = SENT_OK;
    return m_sentMsg;
}
Also used : SMTPMessage(com.sun.mail.smtp.SMTPMessage) InternetAddress(javax.mail.internet.InternetAddress) SendFailedException(javax.mail.SendFailedException) Address(javax.mail.Address) InternetAddress(javax.mail.internet.InternetAddress) MessagingException(javax.mail.MessagingException) AuthenticationFailedException(javax.mail.AuthenticationFailedException) MessagingException(javax.mail.MessagingException) AuthenticationFailedException(javax.mail.AuthenticationFailedException) SendFailedException(javax.mail.SendFailedException) IOException(java.io.IOException) Session(javax.mail.Session)

Example 2 with AuthenticationFailedException

use of javax.mail.AuthenticationFailedException in project sling by apache.

the class SimpleMailServiceIT method sendWithoutAuthentication.

@Test
public void sendWithoutAuthentication() throws Exception {
    final Dictionary<String, Object> properties = MailBuilderConfigurations.minimal();
    createFactoryConfiguration(FACTORY_PID, properties);
    final MessageService messageService = getService(MessageService.class);
    final CompletableFuture<Result> future = messageService.send("simple test message", "recipient@example.net");
    try {
        future.get();
    } catch (Exception e) {
        logger.info(e.getMessage(), e);
        assertTrue(ExceptionUtils.getRootCause(e) instanceof AuthenticationFailedException);
    }
}
Also used : AuthenticationFailedException(javax.mail.AuthenticationFailedException) MessageService(org.apache.sling.commons.messaging.MessageService) AuthenticationFailedException(javax.mail.AuthenticationFailedException) Result(org.apache.sling.commons.messaging.Result) MailResult(org.apache.sling.commons.messaging.mail.MailResult) Test(org.junit.Test)

Example 3 with AuthenticationFailedException

use of javax.mail.AuthenticationFailedException in project oxTrust by GluuFederation.

the class UpdateOrganizationAction method verifySmtpConfiguration.

public String verifySmtpConfiguration() {
    log.info("HostName: " + appliance.getSmtpHost() + " Port: " + appliance.getSmtpPort() + " RequireSSL: " + appliance.isRequiresSsl() + " RequireSSL: " + appliance.isRequiresAuthentication());
    log.info("UserName: " + appliance.getSmtpUserName() + " Password: " + applianceService.getDecryptedSmtpPassword(appliance));
    try {
        MailUtils mail = new MailUtils(appliance.getSmtpHost(), appliance.getSmtpPort(), appliance.isRequiresSsl(), appliance.isRequiresAuthentication(), appliance.getSmtpUserName(), applianceService.getDecryptedSmtpPassword(appliance));
        mail.sendMail(appliance.getSmtpFromName() + " <" + appliance.getSmtpFromEmailAddress() + ">", appliance.getSmtpFromEmailAddress(), "SMTP Server Configuration Verification", "SMTP Server Configuration Verification Successful.");
    } catch (AuthenticationFailedException ex) {
        log.error("SMTP Authentication Error: ", ex);
        return OxTrustConstants.RESULT_FAILURE;
    } catch (MessagingException ex) {
        log.error("SMTP Host Connection Error", ex);
        return OxTrustConstants.RESULT_FAILURE;
    }
    log.info("Connection Successful");
    return OxTrustConstants.RESULT_SUCCESS;
}
Also used : AuthenticationFailedException(javax.mail.AuthenticationFailedException) MessagingException(javax.mail.MessagingException) MailUtils(org.gluu.oxtrust.util.MailUtils)

Example 4 with AuthenticationFailedException

use of javax.mail.AuthenticationFailedException in project pentaho-platform by pentaho.

the class EmailComponent method executeAction.

@Override
public boolean executeAction() {
    EmailAction emailAction = (EmailAction) getActionDefinition();
    String messagePlain = emailAction.getMessagePlain().getStringValue();
    String messageHtml = emailAction.getMessageHtml().getStringValue();
    String subject = emailAction.getSubject().getStringValue();
    String to = emailAction.getTo().getStringValue();
    String cc = emailAction.getCc().getStringValue();
    String bcc = emailAction.getBcc().getStringValue();
    String from = emailAction.getFrom().getStringValue(defaultFrom);
    if (from.trim().length() == 0) {
        from = defaultFrom;
    }
    if (ComponentBase.debug) {
        // $NON-NLS-1$
        debug(Messages.getInstance().getString("Email.DEBUG_TO_FROM", to, from));
        // $NON-NLS-1$
        debug(Messages.getInstance().getString("Email.DEBUG_CC_BCC", cc, bcc));
        // $NON-NLS-1$
        debug(Messages.getInstance().getString("Email.DEBUG_SUBJECT", subject));
        // $NON-NLS-1$
        debug(Messages.getInstance().getString("Email.DEBUG_PLAIN_MESSAGE", messagePlain));
        // $NON-NLS-1$
        debug(Messages.getInstance().getString("Email.DEBUG_HTML_MESSAGE", messageHtml));
    }
    if ((to == null) || (to.trim().length() == 0)) {
        // Get the output stream that the feedback is going into
        OutputStream feedbackStream = getFeedbackOutputStream();
        if (feedbackStream != null) {
            createFeedbackParameter("to", Messages.getInstance().getString("Email.USER_ENTER_EMAIL_ADDRESS"), "", "", // $NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
            true);
            // $NON-NLS-1$
            setFeedbackMimeType("text/html");
            return true;
        } else {
            return false;
        }
    }
    if (subject == null) {
        // $NON-NLS-1$
        error(Messages.getInstance().getErrorString("Email.ERROR_0005_NULL_SUBJECT", getActionName()));
        return false;
    }
    if ((messagePlain == null) && (messageHtml == null)) {
        // $NON-NLS-1$
        error(Messages.getInstance().getErrorString("Email.ERROR_0006_NULL_BODY", getActionName()));
        return false;
    }
    if (getRuntimeContext().isPromptPending()) {
        return true;
    }
    try {
        Properties props = new Properties();
        final IEmailService service = PentahoSystem.get(IEmailService.class, "IEmailService", PentahoSessionHolder.getSession());
        props.put("mail.smtp.host", service.getEmailConfig().getSmtpHost());
        props.put("mail.smtp.port", ObjectUtils.toString(service.getEmailConfig().getSmtpPort()));
        props.put("mail.transport.protocol", service.getEmailConfig().getSmtpProtocol());
        props.put("mail.smtp.starttls.enable", ObjectUtils.toString(service.getEmailConfig().isUseStartTls()));
        props.put("mail.smtp.auth", ObjectUtils.toString(service.getEmailConfig().isAuthenticate()));
        props.put("mail.smtp.ssl", ObjectUtils.toString(service.getEmailConfig().isUseSsl()));
        props.put("mail.smtp.quitwait", ObjectUtils.toString(service.getEmailConfig().isSmtpQuitWait()));
        props.put("mail.from.default", service.getEmailConfig().getDefaultFrom());
        String fromName = service.getEmailConfig().getFromName();
        if (StringUtils.isEmpty(fromName)) {
            fromName = Messages.getInstance().getString("schedulerEmailFromName");
        }
        props.put("mail.from.name", fromName);
        props.put("mail.debug", ObjectUtils.toString(service.getEmailConfig().isDebug()));
        Session session;
        if (service.getEmailConfig().isAuthenticate()) {
            props.put("mail.userid", service.getEmailConfig().getUserId());
            props.put("mail.password", decrypt(service.getEmailConfig().getPassword()));
            Authenticator authenticator = new EmailAuthenticator();
            session = Session.getInstance(props, authenticator);
        } else {
            session = Session.getInstance(props);
        }
        // debugging is on if either component (xaction) or email config debug is on
        if (service.getEmailConfig().isDebug() || ComponentBase.debug) {
            session.setDebug(true);
        }
        // construct the message
        MimeMessage msg = new MimeMessage(session);
        if (from != null) {
            msg.setFrom(new InternetAddress(from));
        } else {
            // There should be no way to get here
            // $NON-NLS-1$
            error(Messages.getInstance().getString("Email.ERROR_0012_FROM_NOT_DEFINED"));
        }
        if ((to != null) && (to.trim().length() > 0)) {
            msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
        }
        if ((cc != null) && (cc.trim().length() > 0)) {
            msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false));
        }
        if ((bcc != null) && (bcc.trim().length() > 0)) {
            msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false));
        }
        if (subject != null) {
            msg.setSubject(subject, LocaleHelper.getSystemEncoding());
        }
        EmailAttachment[] emailAttachments = emailAction.getAttachments();
        if ((messagePlain != null) && (messageHtml == null) && (emailAttachments.length == 0)) {
            msg.setText(messagePlain, LocaleHelper.getSystemEncoding());
        } else if (emailAttachments.length == 0) {
            if (messagePlain != null) {
                // $NON-NLS-1$
                msg.setContent(messagePlain, "text/plain; charset=" + LocaleHelper.getSystemEncoding());
            }
            if (messageHtml != null) {
                // $NON-NLS-1$
                msg.setContent(messageHtml, "text/html; charset=" + LocaleHelper.getSystemEncoding());
            }
        } else {
            // need to create a multi-part message...
            // create the Multipart and add its parts to it
            Multipart multipart = new MimeMultipart();
            // create and fill the first message part
            if (messageHtml != null) {
                // create and fill the first message part
                MimeBodyPart htmlBodyPart = new MimeBodyPart();
                // $NON-NLS-1$
                htmlBodyPart.setContent(messageHtml, "text/html; charset=" + LocaleHelper.getSystemEncoding());
                multipart.addBodyPart(htmlBodyPart);
            }
            if (messagePlain != null) {
                MimeBodyPart textBodyPart = new MimeBodyPart();
                // $NON-NLS-1$
                textBodyPart.setContent(messagePlain, "text/plain; charset=" + LocaleHelper.getSystemEncoding());
                multipart.addBodyPart(textBodyPart);
            }
            for (EmailAttachment element : emailAttachments) {
                IPentahoStreamSource source = element.getContent();
                if (source == null) {
                    // $NON-NLS-1$
                    error(Messages.getInstance().getErrorString("Email.ERROR_0015_ATTACHMENT_FAILED"));
                    return false;
                }
                DataSource dataSource = new ActivationHelper.PentahoStreamSourceWrapper(source);
                String attachmentName = element.getName();
                if (ComponentBase.debug) {
                    // $NON-NLS-1$
                    debug(Messages.getInstance().getString("Email.DEBUG_ADDING_ATTACHMENT", attachmentName));
                }
                // create the second message part
                MimeBodyPart attachmentBodyPart = new MimeBodyPart();
                // attach the file to the message
                attachmentBodyPart.setDataHandler(new DataHandler(dataSource));
                attachmentBodyPart.setFileName(attachmentName);
                if (ComponentBase.debug) {
                    // $NON-NLS-1$
                    debug(Messages.getInstance().getString("Email.DEBUG_ATTACHMENT_SOURCE", dataSource.getName()));
                }
                multipart.addBodyPart(attachmentBodyPart);
            }
            // add the Multipart to the message
            msg.setContent(multipart);
        }
        // $NON-NLS-1$
        msg.setHeader("X-Mailer", EmailComponent.MAILER);
        msg.setSentDate(new Date());
        Transport.send(msg);
        if (ComponentBase.debug) {
            // $NON-NLS-1$
            debug(Messages.getInstance().getString("Email.DEBUG_EMAIL_SUCCESS"));
        }
        return true;
    // TODO: persist the content set for a while...
    } catch (SendFailedException e) {
        // $NON-NLS-1$
        error(Messages.getInstance().getErrorString("Email.ERROR_0011_SEND_FAILED", to), e);
    /*
       * Exception ne; MessagingException sfe = e; while ((ne = sfe.getNextException()) != null && ne instanceof
       * MessagingException) { sfe = (MessagingException) ne;
       * error(Messages.getInstance().getErrorString("Email.ERROR_0011_SEND_FAILED", sfe.toString()), sfe);
       * //$NON-NLS-1$ }
       */
    } catch (AuthenticationFailedException e) {
        // $NON-NLS-1$
        error(Messages.getInstance().getString("Email.ERROR_0014_AUTHENTICATION_FAILED", to), e);
    } catch (Throwable e) {
        // $NON-NLS-1$
        error(Messages.getInstance().getErrorString("Email.ERROR_0011_SEND_FAILED", to), e);
    }
    return false;
}
Also used : InternetAddress(javax.mail.internet.InternetAddress) Multipart(javax.mail.Multipart) MimeMultipart(javax.mail.internet.MimeMultipart) SendFailedException(javax.mail.SendFailedException) AuthenticationFailedException(javax.mail.AuthenticationFailedException) EmailAttachment(org.pentaho.actionsequence.dom.actions.EmailAttachment) OutputStream(java.io.OutputStream) DataHandler(javax.activation.DataHandler) Properties(java.util.Properties) IPentahoStreamSource(org.pentaho.commons.connection.IPentahoStreamSource) Date(java.util.Date) DataSource(javax.activation.DataSource) MimeMessage(javax.mail.internet.MimeMessage) MimeMultipart(javax.mail.internet.MimeMultipart) ActivationHelper(org.pentaho.commons.connection.ActivationHelper) EmailAction(org.pentaho.actionsequence.dom.actions.EmailAction) MimeBodyPart(javax.mail.internet.MimeBodyPart) IEmailService(org.pentaho.platform.api.email.IEmailService) Authenticator(javax.mail.Authenticator) Session(javax.mail.Session)

Example 5 with AuthenticationFailedException

use of javax.mail.AuthenticationFailedException in project epadd by ePADD.

the class VerifyEmailSetup method run.

public static Pair<Boolean, String> run() {
    PrintStream savedOut = System.out;
    InputStream savedIn = System.in;
    try {
        // Get a Properties object
        Properties props = System.getProperties();
        // Get a Session object
        Session session = Session.getInstance(props, null);
        session.setDebug(true);
        String filename = System.getProperty("java.io.tmpdir") + File.separatorChar + "verifyEmailSetup";
        PrintStream ps = new PrintStream(new FileOutputStream(filename));
        System.setOut(ps);
        System.setErr(ps);
        // Get a Store object
        Store store = null;
        store = session.getStore("imaps");
        // not the real password. unfortunately, the checkmuse a/c will get blocked by google.
        store.connect("imap.gmail.com", 993, "checkmuse", "");
        // Folder folder = store.getFolder("[Gmail]/Sent Mail");
        // int totalMessages = folder.getMessageCount();
        // System.err.println (totalMessages + " messages!");
        ps.close();
        String contents = Util.getFileContents(filename);
        System.out.println(contents);
        return new Pair<>(Boolean.TRUE, contents);
    } catch (AuthenticationFailedException e) {
        /* its ok if auth failed. we only want to check if IMAPS network route is blocked.
			 when network is blocked, we'll get something like
			javax.mail.MessagingException: No route to host; 
			nested exception is: 
			java.net.NoRouteToHostException: No route to host 
			...
			*/
        log.info("Verification succeeded: " + Util.stackTrace(e));
        return new Pair<>(Boolean.TRUE, "");
    } catch (Exception e) {
        log.warn("Verification failed: " + Util.stackTrace(e));
        // stack track reveals too much about our code... Util.stackTrace(e));
        return new Pair<>(Boolean.FALSE, e.toString());
    } finally {
        System.setOut(savedOut);
        System.setIn(savedIn);
    }
}
Also used : PrintStream(java.io.PrintStream) AuthenticationFailedException(javax.mail.AuthenticationFailedException) InputStream(java.io.InputStream) FileOutputStream(java.io.FileOutputStream) Store(javax.mail.Store) Properties(java.util.Properties) AuthenticationFailedException(javax.mail.AuthenticationFailedException) Session(javax.mail.Session) Pair(edu.stanford.muse.util.Pair)

Aggregations

AuthenticationFailedException (javax.mail.AuthenticationFailedException)10 Session (javax.mail.Session)6 Properties (java.util.Properties)5 MessagingException (javax.mail.MessagingException)5 InternetAddress (javax.mail.internet.InternetAddress)4 IOException (java.io.IOException)3 Date (java.util.Date)3 SendFailedException (javax.mail.SendFailedException)3 MimeMessage (javax.mail.internet.MimeMessage)3 DataHandler (javax.activation.DataHandler)2 Address (javax.mail.Address)2 Multipart (javax.mail.Multipart)2 Store (javax.mail.Store)2 MimeBodyPart (javax.mail.internet.MimeBodyPart)2 MimeMultipart (javax.mail.internet.MimeMultipart)2 SMTPMessage (com.sun.mail.smtp.SMTPMessage)1 MailConnectException (com.sun.mail.util.MailConnectException)1 Pair (edu.stanford.muse.util.Pair)1 FileNotFoundException (java.io.FileNotFoundException)1 FileOutputStream (java.io.FileOutputStream)1