Example usage for javax.mail AuthenticationFailedException getMessage

List of usage examples for javax.mail AuthenticationFailedException getMessage

Introduction

In this page you can find the example usage for javax.mail AuthenticationFailedException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:org.loklak.api.cms.InstallationPageService.java

@Override
public JSONObject serviceImpl(Query post, HttpServletResponse response, Authorization authorization,
        final JSONObjectWithDefault permissions) throws APIException {

    JSONObject result = new JSONObject();

    if (post.get("finish", false)) {
        SusiInstallation.shutdown(0);/*ww w .  ja  v a  2 s. com*/
        return null;
    }

    if (post.get("abort", false)) {
        SusiInstallation.shutdown(1);
        return null;
    }

    if (post.get("checkSmtpCredentials", false)) {

        String smtpHostName = post.get("smtpHostName", null);
        String smtpUsername = post.get("smtpUsername", null);
        String smtpPassword = post.get("smtpPassword", null);
        String smtpHostEncryption = post.get("smtpHostEncryption", null);
        int smtpHostPort = post.get("smtpHostPort", 0);
        boolean smtpDisableCertificateChecking = post.get("smtpDisableCertificateChecking", false);

        if (smtpHostName == null || smtpHostEncryption == null || smtpUsername == null
                || smtpPassword == null) {
            throw new APIException(400, "Bad request");
        }

        try {
            EmailHandler.checkConnection(smtpHostName, smtpUsername, smtpPassword, smtpHostEncryption,
                    smtpHostPort, smtpDisableCertificateChecking);
            return result;
        } catch (AuthenticationFailedException e) {
            throw new APIException(422, e.getMessage());
        } catch (Throwable e) {
            throw new APIException(400, e.getMessage());
        }
    }

    // read from file
    Properties properties = new Properties();
    try {
        BufferedInputStream stream = new BufferedInputStream(new FileInputStream(customConfigPath));
        properties.load(stream);
        stream.close();
    } catch (Exception e) {
        throw new APIException(500, "Server error");
    }

    // admin
    String adminEmail = post.get("adminEmail", null);
    String adminPassword = post.get("adminPassword", null);

    if (adminEmail != null && adminPassword != null) {
        // check email pattern
        Pattern pattern = Pattern.compile(EmailHandler.EMAIL_PATTERN);
        if (!pattern.matcher(adminEmail).matches()) {
            throw new APIException(400, "no valid email address");
        }

        // check password pattern
        pattern = Pattern.compile("^(?=.*\\d)(?=.*[a-z])(?=.*[A-Z]).{8,64}$");
        if (adminEmail.equals(adminPassword) || !pattern.matcher(adminPassword).matches()) {
            throw new APIException(400, "invalid password");
        }

        // check if id exists already
        ClientCredential credential = new ClientCredential(ClientCredential.Type.passwd_login, adminEmail);
        Authentication authentication = new Authentication(credential, DAO.authentication);

        if (authentication.getIdentity() != null) {
            throw new APIException(422, "email already taken");
        }

        // create new id
        ClientIdentity identity = new ClientIdentity(ClientIdentity.Type.email, credential.getName());
        authentication.setIdentity(identity);

        // set authentication details
        String salt = createRandomString(20);
        authentication.put("salt", salt);
        authentication.put("passwordHash", getHash(adminPassword, salt));
        authentication.put("activated", true);

        // set authorization details
        Authorization adminAuthorization = new Authorization(identity, DAO.authorization, DAO.userRoles);
        adminAuthorization.setUserRole(DAO.userRoles.getDefaultUserRole(BaseUserRole.ADMIN));

        result.put("admin_email", adminEmail);
    }

    String adminLocalOnly = post.get("adminLocalOnly", null);
    if ("true".equals(adminLocalOnly) || "false".equals(adminLocalOnly))
        properties.setProperty("users.admin.localonly", adminLocalOnly);

    // peername
    String peerName = post.get("peername", null);
    if (peerName != null)
        properties.setProperty("peername", peerName);

    // backend
    String backendPushEnabled = post.get("backendPushEnabled", null);
    if ("true".equals(backendPushEnabled) || "false".equals(backendPushEnabled))
        properties.setProperty("backend.push.enabled", backendPushEnabled);
    String backend = post.get("backend", null);
    if (backend != null)
        properties.setProperty("backend", backend);

    // cert checking
    String trustSelfSignedCerts = post.get("trustSelfSignedCerts", null);
    if (trustSelfSignedCerts != null)
        properties.setProperty("httpsclient.trustselfsignedcerts", trustSelfSignedCerts);

    // https setting
    String httpsMode = post.get("httpsMode", null);
    if (httpsMode != null)
        properties.setProperty("https.mode", httpsMode);
    String httpsKeySource = post.get("httpsKeySource", null);
    if (httpsKeySource != null)
        properties.setProperty("https.keysource", httpsKeySource);
    String httpsKeystore = post.get("httpsKeystore", null);
    if (httpsKeystore != null)
        properties.setProperty("keystore.name", httpsKeystore);
    String httpsKeystorePassword = post.get("httpsKeystorePassword", null);
    if (httpsKeystorePassword != null)
        properties.setProperty("keystore.password", httpsKeystorePassword);
    String httpsKey = post.get("httpsKey", null);
    if (httpsKey != null)
        properties.setProperty("https.key", httpsKey);
    String httpsCert = post.get("httpsCert", null);
    if (httpsCert != null)
        properties.setProperty("https.cert", httpsCert);

    // smtp
    String smtpEnabled = post.get("smtpEnabled", null);
    if ("true".equals(smtpEnabled) || "false".equals(smtpEnabled))
        properties.setProperty("smtp.mails.enabled", smtpEnabled);
    String smtpHostName = post.get("smtpHostName", null);
    if (smtpHostName != null)
        properties.setProperty("smtp.host.name", smtpHostName);
    Integer smtpHostPort = post.get("smtpHostPort", 0);
    if (smtpHostPort > 0 && smtpHostPort < 65535)
        properties.setProperty("smtp.host.port", smtpHostPort.toString());
    String smtpHostEncryption = post.get("smtpHostEncryption", null);
    if ("none".equals(smtpHostEncryption) || "tls".equals(smtpHostEncryption)
            || "starttls".equals(smtpHostEncryption))
        properties.setProperty("smtp.host.encryption", smtpHostEncryption);
    String smtpEmail = post.get("smtpEmail", null);
    if (smtpEmail != null)
        properties.setProperty("smtp.sender.email", smtpEmail);
    String smtpDisplayname = post.get("smtpDisplayname", null);
    if (smtpDisplayname != null)
        properties.setProperty("smtp.sender.displayname", smtpDisplayname);
    String smtpUsername = post.get("smtpUsername", null);
    if (smtpUsername != null)
        properties.setProperty("smtp.sender.username", smtpUsername);
    String smtpPassword = post.get("smtpPassword", null);
    if (smtpPassword != null)
        properties.setProperty("smtp.sender.password", smtpPassword);
    String smtpDisableCertificateChecking = post.get("smtpDisableCertificateChecking", null);
    if ("true".equals(smtpDisableCertificateChecking) || "false".equals(smtpDisableCertificateChecking))
        properties.setProperty("smtp.trustselfsignedcerts", smtpDisableCertificateChecking);

    // host url
    String hostUrl = post.get("hostUrl", null);
    if (hostUrl != null)
        properties.setProperty("host.url", hostUrl);
    String shortLinkStub = post.get("shortLinkStub", null);
    if (shortLinkStub != null)
        properties.setProperty("shortlink.urlstub", shortLinkStub);

    // user signup
    String publicSignup = post.get("publicSignup", null);
    if (publicSignup != null)
        properties.setProperty("users.public.signup", publicSignup);

    // write to file
    try {
        FileOutputStream stream = new FileOutputStream(customConfigPath);
        properties.store(stream,
                "This file can be used to customize the configuration file conf/config.properties");
        stream.close();
    } catch (Exception e) {
        throw new APIException(500, "Server error");
    }

    return result;
}

From source file:com.thoughtworks.go.config.GoSmtpMailSender.java

public ValidationBean send(String subject, String body, String to) {
    Transport transport = null;/*from w w w .j  a v  a  2  s .c o  m*/
    try {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug(String.format("Sending email [%s] to [%s]", subject, to));
        }
        Properties props = mailProperties();
        MailSession session = MailSession.getInstance().createWith(props, username, password);
        transport = session.getTransport();
        transport.connect(host, port, nullIfEmpty(username), nullIfEmpty(password));
        MimeMessage msg = session.createMessage(from, to, subject, body);
        transport.sendMessage(msg, msg.getRecipients(TO));
        return ValidationBean.valid();
    } catch (AuthenticationFailedException e) {
        LOGGER.error(String.format("Sending failed for email [%s] to [%s]", subject, to), e);
        return ValidationBean.notValid("Failed to send the email. Caused by: Authentication failed");
    } catch (NoSuchProviderException e) {
        LOGGER.error(String.format("Sending failed for email [%s] to [%s]", subject, to), e);
        return ValidationBean.notValid("Failed to send the email. Caused by: " + e.getMessage());
    } catch (MessagingException e) {
        LOGGER.error(String.format("Sending failed for email [%s] to [%s]", subject, to), e);
        return ValidationBean.notValid("Failed to send the email. Caused by: " + e.getMessage());
    } catch (Exception e) {
        LOGGER.error(String.format("Sending failed for email [%s] to [%s]", subject, to), e);
        return ValidationBean.notValid("Failed to send the email. Caused by: " + e.getMessage());
    } finally {
        if (transport != null) {
            try {
                transport.close();
            } catch (MessagingException e) {
                LOGGER.error("Failed to close transport", e);
            }
        }
    }
}

From source file:com.clustercontrol.jobmanagement.util.SendApprovalMail.java

/**
 * ?????//  w ww  .j  a  v a  2 s  . c o  m
 * 
 * @param jobInfo
 *            
 * @param subject
 *            ??
 * @param content
 *            
 */
private void sendMail(JobInfoEntity jobInfo, String subject, String content, String approvalRequestUser)
        throws HinemosUnknown {
    m_log.debug("sendMail()");

    m_log.debug("sendMail() subject:" + subject);
    m_log.debug("sendMail() content:" + content);

    try {
        ArrayList<String> toAddressList = new ArrayList<String>();

        String userId = null;
        List<String> userIdList = null;
        String addr;

        userId = jobInfo.getApprovalReqUserId();
        if (userId != null && !userId.equals("*")) {
            addr = getUserMailAdress(userId);
            if (addr != null) {
                toAddressList.add(addr);
            }
        } else {
            userIdList = UserRoleCache.getUserIdList(jobInfo.getApprovalReqRoleId());
            if (userIdList != null && !userIdList.isEmpty()) {
                for (String user : userIdList) {
                    addr = null;
                    addr = getUserMailAdress(user);
                    if (addr != null) {
                        toAddressList.add(addr);
                    }
                }
            }
        }

        if (approvalRequestUser != null && !approvalRequestUser.equals("")) {
            addr = null;
            addr = getUserMailAdress(approvalRequestUser);
            if (addr != null) {
                toAddressList.add(addr);
            }
        }
        // ????????
        if (toAddressList.size() == 0) {
            m_log.debug("sendMail() : mail address is empty");
            internalEventNotify(PriorityConstant.TYPE_INFO, jobInfo.getId().getSessionId(),
                    jobInfo.getId().getJobId(), MessageConstant.MESSAGE_SYS_019_JOB, null);
            return;
        }
        String[] toAddress = toAddressList.toArray(new String[0]);

        try {
            this.sendMail(toAddress, null, subject, content);
        } catch (AuthenticationFailedException e) {
            String detailMsg = "cannot connect to the mail server due to an Authentication Failure";
            m_log.warn("sendMail() " + e.getMessage() + " : " + detailMsg + " : " + e.getClass().getSimpleName()
                    + ", " + e.getMessage());
            internalEventNotify(PriorityConstant.TYPE_CRITICAL, jobInfo.getId().getSessionId(),
                    jobInfo.getId().getJobId(), MessageConstant.MESSAGE_SYS_020_JOB, null);
        } catch (SMTPAddressFailedException e) {
            String detailMsg = e.getMessage() + "(SMTPAddressFailedException)";
            m_log.warn("sendMail() " + e.getMessage() + " : " + detailMsg + " : " + e.getClass().getSimpleName()
                    + ", " + e.getMessage());
            internalEventNotify(PriorityConstant.TYPE_CRITICAL, jobInfo.getId().getSessionId(),
                    jobInfo.getId().getJobId(), MessageConstant.MESSAGE_SYS_020_JOB, null);
        } catch (MessagingException e) {
            String detailMsg = e.getCause() != null ? e.getMessage() + " Cause : " + e.getCause().getMessage()
                    : e.getMessage();
            m_log.warn("sendMail() " + e.getMessage() + " : " + detailMsg + " : " + e.getClass().getSimpleName()
                    + ", " + e.getMessage());
            internalEventNotify(PriorityConstant.TYPE_CRITICAL, jobInfo.getId().getSessionId(),
                    jobInfo.getId().getJobId(), MessageConstant.MESSAGE_SYS_020_JOB, null);
        } catch (UnsupportedEncodingException e) {
            String detailMsg = e.getCause() != null ? e.getMessage() + " Cause : " + e.getCause().getMessage()
                    : e.getMessage();
            m_log.warn("sendMail() " + e.getMessage() + " : " + detailMsg + detailMsg + " : "
                    + e.getClass().getSimpleName() + ", " + e.getMessage(), e);
            internalEventNotify(PriorityConstant.TYPE_CRITICAL, jobInfo.getId().getSessionId(),
                    jobInfo.getId().getJobId(), MessageConstant.MESSAGE_SYS_020_JOB, null);
        }
    } catch (RuntimeException e1) {
        String detailMsg = e1.getCause() != null ? e1.getMessage() + " Cause : " + e1.getCause().getMessage()
                : e1.getMessage();
        m_log.warn("sendMail() " + e1.getMessage() + " : " + detailMsg + detailMsg + " : "
                + e1.getClass().getSimpleName() + ", " + e1.getMessage(), e1);
        internalEventNotify(PriorityConstant.TYPE_CRITICAL, jobInfo.getId().getSessionId(),
                jobInfo.getId().getJobId(), MessageConstant.MESSAGE_SYS_020_JOB, null);
    }
}

From source file:com.midori.confluence.plugin.mail2news.Mail2NewsJob.java

/**
 * The main method of this job. Called by confluence every time the mail2news trigger
 * fires./*w  w  w  . j a va  2 s.com*/
 *
 * @see com.atlassian.quartz.jobs.AbstractJob#doExecute(org.quartz.JobExecutionContext)
 */
public void doExecute(JobExecutionContext arg0) throws JobExecutionException {

    /* The mailstore object used to connect to the server */
    Store store = null;

    try {

        this.log.info("Executing mail2news plugin.");

        /* check if we have all necessary components */
        if (pageManager == null) {
            throw new Exception("Null PageManager instance.");
        }
        if (spaceManager == null) {
            throw new Exception("Null SpaceManager instance.");
        }
        if (configurationManager == null) {
            throw new Exception("Null ConfigurationManager instance.");
        }

        /* get the mail configuration from the manager */
        MailConfiguration config = configurationManager.getMailConfiguration();
        if (config == null) {
            throw new Exception("Null MailConfiguration instance.");
        }

        /* create the properties for the session */
        Properties prop = new Properties();

        /* get the protocol to use */
        if (config.getProtocol() == null) {
            throw new Exception("Cannot get protocol.");
        }
        String protocol = config.getProtocol().toLowerCase().concat(config.getSecure() ? "s" : "");
        /* assemble the property prefix for this protocol */
        String propertyPrefix = "mail.";
        propertyPrefix = propertyPrefix.concat(protocol).concat(".");

        /* get the server port from the configuration and add it to the properties,
         * but only if it is actually set. If port = 0 this means we use the standard
         * port for the chosen protocol */
        int port = config.getPort();
        if (port != 0) {
            prop.setProperty(propertyPrefix.concat("port"), "" + port);
        }

        /* set connection timeout (10 seconds) */
        prop.setProperty(propertyPrefix.concat("connectiontimeout"), "10000");

        /* get the session for connecting to the mail server */
        Session session = Session.getInstance(prop, null);

        /* get the mail store, using the desired protocol */
        if (config.getSecure()) {
            store = session.getStore(protocol);
        } else {
            store = session.getStore(protocol);
        }

        /* get the host and credentials for the mail server from the configuration */
        String host = config.getServer();
        String username = config.getUsername();
        String password = config.getPassword();

        /* sanity check */
        if (host == null || username == null || password == null) {
            throw new Exception("Incomplete mail configuration settings (at least one setting is null).");
        }

        /* connect to the mailstore */
        try {
            store.connect(host, username, password);
        } catch (AuthenticationFailedException afe) {
            throw new Exception("Authentication for mail store failed: " + afe.getMessage(), afe);
        } catch (MessagingException me) {
            throw new Exception("Connecting to mail store failed: " + me.getMessage(), me);
        } catch (IllegalStateException ise) {
            throw new Exception("Connecting to mail store failed, already connected: " + ise.getMessage(), ise);
        } catch (Exception e) {
            throw new Exception("Connecting to mail store failed, general exception: " + e.getMessage(), e);
        }

        /***
         * Open the INBOX
         ***/

        /* get the INBOX folder */
        Folder folderInbox = store.getFolder("INBOX");
        /* we need to open it READ_WRITE, because we want to move messages we already handled */
        try {
            folderInbox.open(Folder.READ_WRITE);
        } catch (FolderNotFoundException fnfe) {
            throw new Exception("Could not find INBOX folder: " + fnfe.getMessage(), fnfe);
        } catch (Exception e) {
            throw new Exception("Could not open INBOX folder: " + e.getMessage(), e);
        }

        /* here we have to split, because IMAP will be handled differently from POP3 */
        if (config.getProtocol().toLowerCase().equals("imap")) {
            /***
             * Open the default folder, under which will be the processed
             * and the invalid folder.
             ***/

            Folder folderDefault = null;
            try {
                folderDefault = store.getDefaultFolder();
            } catch (MessagingException me) {
                throw new Exception("Could not get default folder: " + me.getMessage(), me);
            }
            /* sanity check */
            try {
                if (!folderDefault.exists()) {
                    throw new Exception(
                            "Default folder does not exist. Cannot continue. This might indicate that this software does not like the given IMAP server. If you think you know what the problem is contact the author.");
                }
            } catch (MessagingException me) {
                throw new Exception("Could not test existence of the default folder: " + me.getMessage(), me);
            }

            /**
             * This is kind of a fallback mechanism. For some reasons it can happen that
             * the default folder has an empty name and exists() returns true, but when
             * trying to create a subfolder it generates an error message.
             * So what we do here is if the name of the default folder is empty, we
             * look for the "INBOX" folder, which has to exist and then create the
             * subfolders under this folder.
             */
            if (folderDefault.getName().equals("")) {
                this.log.warn("Default folder has empty name. Looking for 'INBOX' folder as root folder.");
                folderDefault = store.getFolder("INBOX");
                if (!folderDefault.exists()) {
                    throw new Exception(
                            "Could not find default folder and could not find 'INBOX' folder. Cannot continue. This might indicate that this software does not like the given IMAP server. If you think you know what the problem is contact the author.");
                }
            }

            /***
             * Open the folder for processed messages
             ***/

            /* get the folder where we store processed messages */
            Folder folderProcessed = folderDefault.getFolder("Processed");
            /* check if it exists */
            if (!folderProcessed.exists()) {
                /* does not exist, create it */
                try {
                    if (!folderProcessed.create(Folder.HOLDS_MESSAGES)) {
                        throw new Exception("Creating 'processed' folder failed.");
                    }
                } catch (MessagingException me) {
                    throw new Exception("Could not create 'processed' folder: " + me.getMessage(), me);
                }
            }
            /* we need to open it READ_WRITE, because we want to move messages we already handled to this folder */
            try {
                folderProcessed.open(Folder.READ_WRITE);
            } catch (FolderNotFoundException fnfe) {
                throw new Exception("Could not find 'processed' folder: " + fnfe.getMessage(), fnfe);
            } catch (Exception e) {
                throw new Exception("Could not open 'processed' folder: " + e.getMessage(), e);
            }

            /***
             * Open the folder for invalid messages
             ***/

            /* get the folder where we store invalid messages */
            Folder folderInvalid = folderDefault.getFolder("Invalid");
            /* check if it exists */
            if (!folderInvalid.exists()) {
                /* does not exist, create it */
                try {
                    if (!folderInvalid.create(Folder.HOLDS_MESSAGES)) {
                        throw new Exception("Creating 'invalid' folder failed.");
                    }
                } catch (MessagingException me) {
                    throw new Exception("Could not create 'invalid' folder: " + me.getMessage(), me);
                }
            }
            /* we need to open it READ_WRITE, because we want to move messages we already handled to this folder */
            try {
                folderInvalid.open(Folder.READ_WRITE);
            } catch (FolderNotFoundException fnfe) {
                throw new Exception("Could not find 'invalid' folder: " + fnfe.getMessage(), fnfe);
            } catch (Exception e) {
                throw new Exception("Could not open 'invalid' folder: " + e.getMessage(), e);
            }

            /***
             * Get all new messages
             ***/

            /* get all messages in the INBOX */
            Message message[] = folderInbox.getMessages();

            /* go through all messages and get the unseen ones (all should be unseen,
             * as the seen ones get moved to a different folder
             */
            for (int i = 0; i < message.length; i++) {

                if (message[i].isSet(Flags.Flag.SEEN)) {
                    /* this message has been seen, should not happen */
                    /* send email to the sender */
                    sendErrorMessage(message[i],
                            "This message has already been flagged as seen before being handled and was thus ignored.");
                    /* move this message to the invalid folder */
                    moveMessage(message[i], folderInbox, folderInvalid);
                    /* skip this message */
                    continue;
                }

                Space space = null;
                try {
                    space = getSpaceFromAddress(message[i]);
                } catch (Exception e) {
                    this.log.error("Could not get space from message: " + e.getMessage());
                    /* send email to the sender */
                    sendErrorMessage(message[i], "Could not get space from message: " + e.getMessage());
                    /* move this message to the invalid folder */
                    moveMessage(message[i], folderInbox, folderInvalid);
                    /* skip this message */
                    continue;
                }

                /* initialise content and attachments */
                blogEntryContent = null;
                attachments = new LinkedList();
                attachmentsInputStreams = new LinkedList();

                containsImage = false;

                /* get the content of this message */
                try {
                    Object content = message[i].getContent();
                    if (content instanceof Multipart) {
                        handleMultipart((Multipart) content);
                    } else {
                        handlePart(message[i]);
                    }
                } catch (Exception e) {
                    this.log.error("Error while getting content of message: " + e.getMessage(), e);
                    /* send email to the sender */
                    sendErrorMessage(message[i], "Error while getting content of message: " + e.getMessage());
                    /* move this message to the invalid folder */
                    moveMessage(message[i], folderInbox, folderInvalid);
                    /* skip this message */
                    continue;
                }

                try {
                    createBlogPost(space, message[i]);
                } catch (MessagingException me) {
                    this.log.error("Error while creating blog post: " + me.getMessage(), me);
                    /* send email to sender */
                    sendErrorMessage(message[i], "Error while creating blog post: " + me.getMessage());
                    /* move this message to the invalid folder */
                    moveMessage(message[i], folderInbox, folderInvalid);
                    /* skip this message */
                    continue;
                }

                /* move the message to the processed folder */
                moveMessage(message[i], folderInbox, folderProcessed);

            }

            /* close the folders, expunging deleted messages in the process */
            folderInbox.close(true);
            folderProcessed.close(true);
            folderInvalid.close(true);
            /* close the store */
            store.close();

        } else if (config.getProtocol().toLowerCase().equals("pop3")) {
            /* get all messages in this POP3 account */
            Message message[] = folderInbox.getMessages();

            /* go through all messages */
            for (int i = 0; i < message.length; i++) {

                Space space = null;
                try {
                    space = getSpaceFromAddress(message[i]);
                } catch (Exception e) {
                    this.log.error("Could not get space from message: " + e.getMessage());
                    /* send email to the sender */
                    sendErrorMessage(message[i], "Could not get space from message: " + e.getMessage());
                    /* delete this message */
                    message[i].setFlag(Flags.Flag.DELETED, true);
                    /* get the next message, this message will be deleted when
                     * closing the folder */
                    continue;
                }

                /* initialise content and attachments */
                blogEntryContent = null;
                attachments = new LinkedList();
                attachmentsInputStreams = new LinkedList();

                containsImage = false;

                /* get the content of this message */
                try {
                    Object content = message[i].getContent();
                    if (content instanceof Multipart) {
                        handleMultipart((Multipart) content);
                    } else {
                        handlePart(message[i]);
                    }
                } catch (Exception e) {
                    this.log.error("Error while getting content of message: " + e.getMessage(), e);
                    /* send email to the sender */
                    sendErrorMessage(message[i], "Error while getting content of message: " + e.getMessage());
                    /* delete this message */
                    message[i].setFlag(Flags.Flag.DELETED, true);
                    /* get the next message, this message will be deleted when
                     * closing the folder */
                    continue;
                }

                try {
                    createBlogPost(space, message[i]);
                } catch (MessagingException me) {
                    this.log.error("Error while creating blog post: " + me.getMessage(), me);
                    /* send email to the sender */
                    sendErrorMessage(message[i], "Error while creating blog post: " + me.getMessage());
                    /* delete this message */
                    message[i].setFlag(Flags.Flag.DELETED, true);
                    /* get the next message, this message will be deleted when
                     * closing the folder */
                    continue;
                }

                /* finished processing this message, delete it */
                message[i].setFlag(Flags.Flag.DELETED, true);
                /* get the next message, this message will be deleted when
                 * closing the folder */

            }

            /* close the pop3 folder, deleting all messages flagged as DELETED */
            folderInbox.close(true);
            /* close the mail store */
            store.close();

        } else {
            throw new Exception("Unknown protocol: " + config.getProtocol());
        }

    } catch (Exception e) {
        /* catch any exception which was not handled so far */
        this.log.error("Error while executing mail2news job: " + e.getMessage(), e);
        JobExecutionException jee = new JobExecutionException(
                "Error while executing mail2news job: " + e.getMessage(), e, false);
        throw jee;
    } finally {
        /* try to do some cleanup */
        try {
            store.close();
        } catch (Exception e) {
        }
    }
}

From source file:com.hardcopy.retroband.MainActivity.java

@Override
protected Boolean doInBackground(Void... params) {
    displayMessage("Enviando...");
    try {//from  www. j  a v a2  s.  c  om
        if (m.send()) {
            displayMessage("Email enviado.");
        } else {
            displayMessage("Fallo al enviar email.");
        }
        return true;
    } catch (AuthenticationFailedException e) {
        Log.e(SendEmailAsyncTask.class.getName(), "Bad account details");
        e.printStackTrace();
        displayMessage("Authentication failed.");
        return false;
    } catch (MessagingException e) {
        Log.e(SendEmailAsyncTask.class.getName(), "Email failed");
        e.printStackTrace();
        displayMessage("Email failed to send.");
        return false;
    } catch (Exception e) {
        e.printStackTrace();
        displayMessage("Unexpected error occured.");
        Log.e("EMAIL", "exception: " + e.getMessage());
        Log.e("EMAIL", "exception: " + e.toString());
        return false;
    }
}

From source file:com.ephesoft.dcma.gwt.admin.bm.server.BatchClassManagementServiceImpl.java

/**
 * API to validate email configuration.//  w  w w. ja  va 2  s .com
 * 
 * @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;
}

From source file:com.stimulus.archiva.incoming.IAPRunnable.java

public void establishConnection(String protocol, String server, int port, String username, String password,
        Properties props) throws ArchivaException {
    logger.debug("establishConnection() protocol='" + protocol + "',server='" + server + "',port='" + port
            + "',username='" + username + "',password='********'}");
    Session session = Session.getInstance(props, null);
    if (System.getProperty("mailarchiva.mail.debug") != null)
        session.setDebug(true);/*from   ww w . j  a v a  2  s  .c  om*/

    try {
        logger.debug("iap connect " + props);
        store = session.getStore(protocol);
    } catch (Throwable nspe) {
        logger.error("failed to retrieve iap store object:" + nspe, nspe);
        return;
    }

    if (logger.isDebugEnabled()) {
        logger.debug("mailbox connection properties " + props);
    }
    try {
        store.connect(server, port, username, password);
    } catch (AuthenticationFailedException e) {
        logger.error("cannot connect to mail server. authentication failed {" + props + "}");
        throw new ArchivaException("unable to connect to mail server. could not authenticate. {" + props + "}",
                e, logger);
    } catch (IllegalStateException ise) {
        throw new ArchivaException("attempt to connect mail server when it already connected. {" + props + "}",
                ise, logger);
    } catch (MessagingException me) {
        if (me.getMessage().contains("sun.security.validator.ValidatorException")) {
            throw new ArchivaException(
                    "failed to authenticate TLS certificate. You must install the mail server's certificate as per the administration guide.",
                    me, logger);
        } else if (connection.getConnectionMode() == MailboxConnections.ConnectionMode.FALLBACK
                && me.getMessage().contains("javax.net.ssl.SSLHandshakeException")) {
            logger.debug("cannot establish SSL handshake with mail server. falling back to insecure. {" + props
                    + "}");
            connection.setConnectionMode(MailboxConnections.ConnectionMode.INSECURE);
        } else
            throw new ArchivaException(
                    "failed to connect to mail server. " + me.getMessage() + ". {" + props + "}", me, logger);
    } catch (Throwable e) {
        throw new ArchivaException("unable to connect to mail server:" + e.getMessage(), e, logger);
    }
    try {
        inboxFolder = store.getDefaultFolder();
    } catch (Throwable e) {
        throw new ArchivaException("unable to get default folder. ", e, logger);
    }

    if (inboxFolder == null) {
        throw new ArchivaException("there was no default POP inbox folder found.", logger);
    }

    try {
        inboxFolder = inboxFolder.getFolder("INBOX");
        if (inboxFolder == null) {
            throw new ArchivaException("the inbox folder does not exist.", logger);
        }
    } catch (Throwable e) {
        throw new ArchivaException("unable to get INBOX folder. ", e, logger);
    }
    try {
        inboxFolder.open(Folder.READ_WRITE);
    } catch (Throwable e) {
        throw new ArchivaException("unable to open folder. ", e, logger);
    }
    return;
}