Example usage for javax.mail MessagingException MessagingException

List of usage examples for javax.mail MessagingException MessagingException

Introduction

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

Prototype

public MessagingException(String s, Exception e) 

Source Link

Document

Constructs a MessagingException with the specified Exception and detail message.

Usage

From source file:com.cws.esolutions.core.utils.EmailUtils.java

/**
 * Processes and sends an email message as generated by the requesting
 * application. This method is utilized with a JNDI datasource.
 *
 * @param mailConfig - The {@link com.cws.esolutions.core.config.xml.MailConfig} to utilize
 * @param message - The email message/*from   ww  w  . j ava2  s. c o  m*/
 * @param isWeb - <code>true</code> if this came from a container, <code>false</code> otherwise
 * @throws MessagingException {@link javax.mail.MessagingException} if an exception occurs sending the message
 */
public static final synchronized void sendEmailMessage(final MailConfig mailConfig, final EmailMessage message,
        final boolean isWeb) throws MessagingException {
    final String methodName = EmailUtils.CNAME
            + "#sendEmailMessage(final MailConfig mailConfig, final EmailMessage message, final boolean isWeb) throws MessagingException";

    Session mailSession = null;

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("Value: {}", mailConfig);
        DEBUGGER.debug("Value: {}", message);
        DEBUGGER.debug("Value: {}", isWeb);
    }

    SMTPAuthenticator smtpAuth = null;

    if (DEBUG) {
        DEBUGGER.debug("MailConfig: {}", mailConfig);
    }

    try {
        if (isWeb) {
            Context initContext = new InitialContext();
            Context envContext = (Context) initContext.lookup(EmailUtils.INIT_DS_CONTEXT);

            if (DEBUG) {
                DEBUGGER.debug("InitialContext: {}", initContext);
                DEBUGGER.debug("Context: {}", envContext);
            }

            if (envContext != null) {
                mailSession = (Session) envContext.lookup(mailConfig.getDataSourceName());
            }
        } else {
            Properties mailProps = new Properties();

            try {
                mailProps.load(
                        EmailUtils.class.getClassLoader().getResourceAsStream(mailConfig.getPropertyFile()));
            } catch (NullPointerException npx) {
                try {
                    mailProps.load(new FileInputStream(mailConfig.getPropertyFile()));
                } catch (IOException iox) {
                    throw new MessagingException(iox.getMessage(), iox);
                }
            } catch (IOException iox) {
                throw new MessagingException(iox.getMessage(), iox);
            }

            if (DEBUG) {
                DEBUGGER.debug("Properties: {}", mailProps);
            }

            if (StringUtils.equals((String) mailProps.get("mail.smtp.auth"), "true")) {
                smtpAuth = new SMTPAuthenticator();
                mailSession = Session.getDefaultInstance(mailProps, smtpAuth);
            } else {
                mailSession = Session.getDefaultInstance(mailProps);
            }
        }

        if (DEBUG) {
            DEBUGGER.debug("Session: {}", mailSession);
        }

        if (mailSession == null) {
            throw new MessagingException("Unable to configure email services");
        }

        mailSession.setDebug(DEBUG);
        MimeMessage mailMessage = new MimeMessage(mailSession);

        // Our emailList parameter should contain the following
        // items (in this order):
        // 0. Recipients
        // 1. From Address
        // 2. Generated-From (if blank, a default value is used)
        // 3. The message subject
        // 4. The message content
        // 5. The message id (optional)
        // We're only checking to ensure that the 'from' and 'to'
        // values aren't null - the rest is really optional.. if
        // the calling application sends a blank email, we aren't
        // handing it here.
        if (message.getMessageTo().size() != 0) {
            for (String to : message.getMessageTo()) {
                if (DEBUG) {
                    DEBUGGER.debug(to);
                }

                mailMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
            }

            mailMessage.setFrom(new InternetAddress(message.getEmailAddr().get(0)));
            mailMessage.setSubject(message.getMessageSubject());
            mailMessage.setContent(message.getMessageBody(), "text/html");

            if (message.isAlert()) {
                mailMessage.setHeader("Importance", "High");
            }

            Transport mailTransport = mailSession.getTransport("smtp");

            if (DEBUG) {
                DEBUGGER.debug("Transport: {}", mailTransport);
            }

            mailTransport.connect();

            if (mailTransport.isConnected()) {
                Transport.send(mailMessage);
            }
        }
    } catch (MessagingException mex) {
        throw new MessagingException(mex.getMessage(), mex);
    } catch (NamingException nx) {
        throw new MessagingException(nx.getMessage(), nx);
    }
}

From source file:mitm.application.djigzo.james.matchers.AbstractIsSkipCalendar.java

protected boolean hasMatch(User user) throws MessagingException {
    /*/*from  w w w.  ja  v a2s.c o m*/
     * Return true if user needs to skip a calendar
     */
    try {
        UserProperties properties = user.getUserPreferences().getProperties();

        switch (skipParameter) {
        case SKIP_SMIME:
            return properties.isSMIMESkipCalendar();
        case SKIP_SMIME_SIGNING:
            return properties.isSMIMESkipSigningCalendar();
        case SKIP_SMIME_BOTH:
            return properties.isSMIMESkipCalendar() || properties.isSMIMESkipSigningCalendar();
        default:
            throw new IllegalArgumentException("Unknown skipParameter: " + skipParameter);
        }
    } catch (HierarchicalPropertiesException e) {
        throw new MessagingException("Error in hasMatch.", e);
    }
}

From source file:com.hs.mail.smtp.message.SmtpMessage.java

public MimeMessage getMimeMessage() throws MessagingException {
    Session session = Session.getInstance(System.getProperties(), null);
    InputStream is = null;/*from  w w  w  .  j  a v  a2s  . c o  m*/
    try {
        is = new FileInputStream(getDataFile());
        return new MimeMessage(session, is);
    } catch (FileNotFoundException e) {
        throw new MessagingException(e.getMessage(), e);
    } finally {
        IOUtils.closeQuietly(is);
    }
}

From source file:mitm.application.djigzo.relay.RelayHandler.java

private void extractMessageParts(MimeMessage message) throws MessagingException, IOException {
    /*//from  ww  w.  ja  v  a2s .  c  o m
     * Fast fail. Only multipart mixed messages are supported. 
     */
    if (!message.isMimeType("multipart/mixed")) {
        return;
    }

    Multipart mp;

    try {
        mp = (Multipart) message.getContent();
    } catch (IOException e) {
        throw new MessagingException("Error getting message content.", e);
    }

    for (int i = 0; i < mp.getCount(); i++) {
        BodyPart part = mp.getBodyPart(i);

        if (part.isMimeType("message/rfc822")) {
            relayMessage = BodyPartUtils.extractFromRFC822(part);
        } else if (part.isMimeType("text/xml")) {
            metaPart = part;
        }

        if (metaPart != null && relayMessage != null) {
            break;
        }
    }
}

From source file:gov.nih.nci.cacis.nav.SendEncryptedMail.java

private Certificate getCert(String keyAlias) throws MessagingException {
    Certificate result = null;//  www.  ja  va  2 s  .  co  m
    try {
        result = trustStoreRef.getCertificate(keyAlias);
        // CHECKSTYLE:OFF
    } catch (Exception ex) { // NOPMD
        // CHECKSTYLE:ON
        LOG.error(ERROR_INITALISING_ENCRYPTER, ex);
        throw new MessagingException(ERROR_INITALISING_ENCRYPTER, ex);
    }
    if (result == null) {
        throw new IllegalArgumentException(String.format(
                "Could not find any certificate with key '%s' in truststore '%s'.", keyAlias, truststore));
    }
    return result;
}

From source file:mitm.common.security.smime.handler.SMIMEInfoHandlerImpl.java

private MimeMessage handleSigned(MimeMessage message, SMIMEInspector sMIMEInspector, int level)
        throws MessagingException {
    SMIMESignedInspector signedInspector = sMIMEInspector.getSignedInspector();

    Collection<X509Certificate> certificates = null;

    try {/* w  ww.  j ava 2 s.  c  om*/
        certificates = signedInspector.getCertificates();
    } catch (CryptoMessageSyntaxException e) {
        logger.error("Error getting certificates from signed message.", e);
    }

    Set<String> signerEmail = new HashSet<String>();

    List<SignerInfo> signers;

    try {
        signers = signedInspector.getSigners();
    } catch (CryptoMessageSyntaxException e) {
        throw new MessagingException("Error getting signers.", e);
    }

    Boolean signatureValid = null;

    for (int signerIndex = 0; signerIndex < signers.size(); signerIndex++) {
        Boolean thisSignatureValid = null;

        try {
            SignerInfo signer = signers.get(signerIndex);

            SignerIdentifier signerId;

            try {
                signerId = signer.getSignerId();
            } catch (IOException e) {
                logger.error("Error getting signerId", e);

                /*
                 * Continue with other signers
                 */
                continue;
            }

            addSignerIdentifierInfo(message, signerIndex, signerId, level);

            /*
             * try to get the signing certificate using a certificate selector
             */
            CertSelector certSelector;

            try {
                certSelector = signerId.getSelector();
            } catch (IOException e) {
                logger.error("Error getting selector for signer", e);

                /*
                 * Continue with other signers
                 */
                continue;
            }

            /* first search through the certificates that are embedded in the CMS blob */
            Collection<X509Certificate> signingCerts = CertificateUtils.getMatchingCertificates(certificates,
                    certSelector);

            if (signingCerts.size() == 0 && securityServices.getKeyAndCertStore() != null) {
                /*
                 * the certificate could not be found in the CMS blob. If the CertStore is
                 * set we will see if the CertStore has a match.
                 */
                try {
                    signingCerts = securityServices.getKeyAndCertStore().getCertificates(certSelector);
                } catch (CertStoreException e) {
                    logger.error("Error getting certificates from the CertStore.", e);
                }
            }

            X509Certificate signingCertificate = null;

            if (signingCerts != null && signingCerts.size() > 0) {
                /*
                 * there can be more than one match, although in practice this should not happen
                 * often. Get the first one. If the sender is so stupid to send different
                 * certificates with same issuer/serial, subjectKeyId (which is not likely) than
                 * he/she cannot expect the signature to validate correctly. If the sender did
                 * not add a certificate to the CMS blob but the certificate was found in the
                 * CertStore it can happen that the wrong certificate was found. Solving this
                 * requires that we step through all certificates found an verify until we found
                 * the correct one.
                 */
                signingCertificate = signingCerts.iterator().next();
            }

            if (signingCertificate != null) {
                if (!verifySignature(message, signerIndex, signer, signingCertificate, level)) {
                    thisSignatureValid = false;
                }

                /*
                 * we expect that the certificates from the CMS blob were already added to the stores
                 * if the certificate is not in the store the path cannot be build. It is possible to
                 * add them temporarily to the CertPathBuilder but that's not always as fast as adding
                 * them to the global CertStore.
                 */
                if (!verifySigningCertificate(message, signerIndex, signingCertificate, certificates, level)) {
                    thisSignatureValid = false;
                }

                if (thisSignatureValid == null) {
                    thisSignatureValid = true;
                }

                try {
                    signerEmail.addAll(new X509CertificateInspector(signingCertificate).getEmail());
                } catch (Exception e) {
                    logger.error("Error getting email addresses", e);
                }
            } else {
                String info = "Signing certificate could not be found.";

                logger.warn(info);

                setHeader(SMIMESecurityInfoHeader.SIGNER_VERIFIED + signerIndex, "False", level, message);
                setHeader(SMIMESecurityInfoHeader.SIGNER_VERIFICATION_INFO + signerIndex, info, level, message);
            }
        } finally {
            /*
             * Only make the overall signatureValid true if it was not already set and if the current
             * signature check is valid
             */
            if (BooleanUtils.isTrue(thisSignatureValid) && signatureValid == null) {
                signatureValid = true;
            }

            if (BooleanUtils.isFalse(thisSignatureValid)) {
                signatureValid = false;
            }
        }
    } /* end for */

    onSigned(message, sMIMEInspector, level, BooleanUtils.isTrue(signatureValid), signerEmail);

    return message;
}

From source file:com.sun.mail.pop3.POP3Folder.java

/**
 * Throws <code>FolderNotFoundException</code> unless this
 * folder is named "INBOX"./*from ww  w. ja v  a  2  s . c  o m*/
 *
 * @exception   FolderNotFoundException   if not INBOX
 * @exception   AuthenticationException   authentication failures
 * @exception   MessagingException   other open failures
 */
public synchronized void open(int mode) throws MessagingException {
    checkClosed();
    if (!exists)
        throw new FolderNotFoundException(this, "folder is not INBOX");

    try {
        port = ((POP3Store) store).getPort(this);
        Status s = port.stat();
        total = s.total;
        size = s.size;
        this.mode = mode;
        opened = true;
    } catch (IOException ioex) {
        try {
            if (port != null)
                port.quit();
        } catch (IOException ioex2) {
            // ignore
        } finally {
            port = null;
            ((POP3Store) store).closePort(this);
        }
        throw new MessagingException("Open failed", ioex);
    }

    // Create the message cache vector of appropriate size
    message_cache = new Vector(total);
    message_cache.setSize(total);
    doneUidl = false;

    notifyConnectionListeners(ConnectionEvent.OPENED);
}

From source file:com.mylab.mail.OpenCmsMailService.java

public void sendMultipartMail(MessageConfig config, DataSource imageds, String image, DataSource audiods,
        String audio) throws MessagingException {
    log.debug("Sending multipart message " + config);

    Session session = getSession();/*from   www . j ava  2 s .c  o  m*/
    MimeMultipart multipart = new MimeMultipart();
    MimeBodyPart html = new MimeBodyPart();
    html.setContent(config.getContent(), config.getContentType());
    html.setHeader("MIME-Version", "1.0");
    html.setHeader("Content-Type", html.getContentType());
    multipart.addBodyPart(html);

    BodyPart messageBodyPart = new MimeBodyPart();
    messageBodyPart.setDataHandler(new DataHandler(imageds));
    messageBodyPart.setFileName(image);
    multipart.addBodyPart(messageBodyPart);

    messageBodyPart = new MimeBodyPart();
    messageBodyPart.setDataHandler(new DataHandler(audiods));
    messageBodyPart.setFileName(audio);
    multipart.addBodyPart(messageBodyPart);

    final MimeMessage message = new MimeMessage(session);
    message.setContent(multipart);
    try {
        message.setFrom(new InternetAddress(config.getFrom(), config.getFromName()));
        addRecipientsWhitelist(message, config.getTo(), config.getToName(), config.getCardconfig());
    } catch (UnsupportedEncodingException ex) {
        throw new MessagingException("Setting from or to failed", ex);
    }

    message.setSubject(config.getSubject());

    // we don't send in a new Thread so that we get the Exception
    Transport.send(message);

}

From source file:mitm.application.djigzo.james.mailets.SenderTemplatePropertySendMail.java

@Override
protected Template getTemplate(Mail mail, final SimpleHash root) throws IOException, MessagingException {
    Template template = null;/*from   ww w. ja v  a2s.  co  m*/

    try {
        InternetAddress originator = messageOriginatorIdentifier.getOriginator(mail);

        if (templateProperty != null && originator != null) {
            User user = userWorkflow.getUser(originator.getAddress(),
                    UserWorkflow.GetUserMode.CREATE_IF_NOT_EXIST);

            template = getTemplateFromUser(user, root);

            /*
             * Get the property values from the user so they can be stored in the template root
             */
            if (userProperties != null) {
                UserProperties properties = user.getUserPreferences().getProperties();

                for (String userProperty : userProperties) {
                    userProperty = StringUtils.trimToNull(userProperty);

                    if (userProperty == null) {
                        continue;
                    }

                    String value = properties.getProperty(userProperty, false);

                    if (value != null) {
                        root.put(userProperty, value);
                    }
                }
            }
        }

        if (template == null) {
            getLogger().debug("No template found for " + originator);
            /*
             * The sender was not a valid user or did not have a template. Use the default static 
             * template specified in the mailet config. 
             */
            template = super.getTemplate(mail, root);
        }
    } catch (HierarchicalPropertiesException e) {
        throw new MessagingException("Error getting template.", e);
    }

    return template;
}

From source file:mitm.application.djigzo.james.mailets.AbstractGeneratePassword.java

@Override
public void initMailet() throws MessagingException {
    super.initMailet();

    initRandomIDBound();/*from w w  w.  j  a v a  2 s.  c  o m*/
    initUniqueID();
    initDefaultPasswordLength();

    try {
        randomGenerator = SecurityFactoryFactory.getSecurityFactory().createSecureRandom();
    } catch (Exception e) {
        throw new MessagingException("SecureRandom instance could not be created", e);
    }

    sessionManager = SystemServices.getSessionManager();

    userWorkflow = SystemServices.getUserWorkflow();

    actionExecutor = DatabaseActionExecutorBuilder.createDatabaseActionExecutor(sessionManager);

    assert (actionExecutor != null);

    StrBuilder sb = new StrBuilder();

    sb.append("randomIDBound: ");
    sb.append(randomIDBound);
    sb.append("; ");
    sb.append("UniqueID: ");
    sb.append(uniqueID);
    sb.append("; ");
    sb.append("defaultPasswordLength: ");
    sb.append(defaultPasswordLength);

    getLogger().info(sb.toString());
}