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:fr.xebia.cloud.amazon.aws.iam.AmazonAwsIamAccountCreator.java

public AmazonAwsIamAccountCreator(Environment environment) {
    this.environment = Preconditions.checkNotNull(environment);
    try {//w ww  .  ja v  a  2  s  .c om
        keyPairGenerator = KeyPairGenerator.getInstance("RSA", BOUNCY_CASTLE_PROVIDER_NAME);
        keyPairGenerator.initialize(1024, new SecureRandom());

        String credentialsFileName = "AwsCredentials-" + environment.getIdentifier() + ".properties";
        InputStream credentialsAsStream = Thread.currentThread().getContextClassLoader()
                .getResourceAsStream(credentialsFileName);
        Preconditions.checkNotNull(credentialsAsStream,
                "File '/" + credentialsFileName + "' NOT found in the classpath");
        AWSCredentials awsCredentials = new PropertiesCredentials(credentialsAsStream);
        iam = new AmazonIdentityManagementClient(awsCredentials);

        ses = new AmazonSimpleEmailServiceClient(awsCredentials);

        ec2 = new AmazonEC2Client(awsCredentials);
        ec2.setEndpoint("ec2.eu-west-1.amazonaws.com");

        InputStream smtpPropertiesAsStream = Thread.currentThread().getContextClassLoader()
                .getResourceAsStream("smtp.properties");
        Preconditions.checkNotNull(smtpPropertiesAsStream,
                "File '/smtp.properties' NOT found in the classpath");

        final Properties smtpProperties = new Properties();
        smtpProperties.load(smtpPropertiesAsStream);

        mailSession = Session.getInstance(smtpProperties, null);
        mailTransport = mailSession.getTransport();
        if (smtpProperties.containsKey("mail.username")) {
            mailTransport.connect(smtpProperties.getProperty("mail.username"),
                    smtpProperties.getProperty("mail.password"));
        } else {
            mailTransport.connect();
        }
        try {
            mailFrom = new InternetAddress(smtpProperties.getProperty("mail.from"));
        } catch (Exception e) {
            throw new MessagingException("Exception parsing 'mail.from' from 'smtp.properties'", e);
        }

    } catch (Exception e) {
        throw Throwables.propagate(e);
    }
}

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

public synchronized void close(boolean expunge) throws MessagingException {
    checkOpen();//w w w  . j  av  a2  s .  co m

    try {
        /*
         * Some POP3 servers will mark messages for deletion when
         * they're read.  To prevent such messages from being
         * deleted before the client deletes them, you can set
         * the mail.pop3.rsetbeforequit property to true.  This
         * causes us to issue a POP3 RSET command to clear all
         * the "marked for deletion" flags.  We can then explicitly
         * delete messages as desired.
         */
        if (((POP3Store) store).rsetBeforeQuit)
            port.rset();
        if (expunge && mode == READ_WRITE) {
            // find all messages marked deleted and issue DELE commands
            POP3Message m;
            for (int i = 0; i < message_cache.size(); i++) {
                if ((m = (POP3Message) message_cache.elementAt(i)) != null) {
                    if (m.isSet(Flags.Flag.DELETED))
                        try {
                            port.dele(i + 1);
                        } catch (IOException ioex) {
                            throw new MessagingException("Exception deleting messages during close", ioex);
                        }
                }
            }
        }

        port.quit();
    } catch (IOException ex) {
        // do nothing
    } finally {
        port = null;
        ((POP3Store) store).closePort(this);
        message_cache = null;
        opened = false;
        notifyConnectionListeners(ConnectionEvent.CLOSED);
    }
}

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

@Override
public Collection<MailAddress> matchMail(Mail mail) throws MessagingException {
    try {//from   w  w  w . ja  va2s . com
        String trigger = getTrigger(mail);

        /*
         * Trigger must be a name value pair:
         * 
         * Header : Reg. Epxr
         * 
         * If there is only a header any value will be accepted 
         */

        if (StringUtils.isNotBlank(trigger)) {
            try {
                String[] pair = StringUtils.stripAll(StringUtils.split(trigger, ":", 2));

                Pattern pattern = Pattern.compile(pair.length > 1 ? pair[1] : ".*");

                Context context = new Context(pair[0], pattern);

                getActivationContext().set(ACTIVATION_CONTEXT_KEY, context);
            } catch (PatternSyntaxException e) {
                logger.warn("Invalid pattern. Trigger: " + trigger, e);
            }
        }

        return super.matchMail(mail);
    } catch (DatabaseException e) {
        throw new MessagingException("Error getting pattern", e);
    }
}

From source file:mitm.common.dlp.impl.MimeMessageTextExtractorImpl.java

private void extractMimeMessageMetaInfo(MimeMessage message, PartContext context) throws MessagingException {
    TextExtractorContext extractorContext = new TextExtractorContextImpl();

    extractorContext.setEncoding(CharEncoding.US_ASCII);
    extractorContext.setName("headers");

    StrBuilder sb = new StrBuilder(4096);

    try {/*from  ww w . j  a  v  a2s .  c o  m*/
        for (Enumeration<?> headerEnum = message.getAllHeaders(); headerEnum.hasMoreElements();) {
            Header header = (Header) headerEnum.nextElement();

            if (header == null) {
                continue;
            }

            if (skipHeaders != null && skipHeaders.contains(StringUtils.lowerCase(header.getName()))) {
                continue;
            }

            sb.append(header.getName()).append(": ").appendln(HeaderUtils.decodeTextQuietly(header.getValue()));
        }
    } catch (MessagingException e) {
        /*
         * Fallback to raw headers
         */
        for (Enumeration<?> headerEnum = message.getAllHeaderLines(); headerEnum.hasMoreElements();) {
            sb.appendln(headerEnum.nextElement());
        }
    }

    byte[] headerBytes = MiscStringUtils.toUTF8Bytes(sb.toString());

    RewindableInputStream input = new RewindableInputStream(new ByteArrayInputStream(headerBytes),
            MEM_THRESHOLD);

    ExtractedPart part = new ExtractedPartImpl(extractorContext, input, headerBytes.length);

    try {
        context.update(part, true /* add */);
    } catch (IOException e) {
        throw new MessagingException("Error adding part to context.", e);
    }
}

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

private void requestCertificate(User user) throws MessagingException {
    try {//w w w.  ja  v  a  2s. co m
        CASettings caSettings = caSettingsProvider.getSettings();

        RequestParameters request = RequestUtils.createRequestParameters(user.getEmail(), caSettings);

        /*
         * Override the certificate request handler from the CASettings if this mailet overrides it
         */
        if (StringUtils.isNotEmpty(certificateRequestHandler)) {
            request.setCertificateRequestHandler(certificateRequestHandler);
        }

        ca.requestCertificate(request);
    } catch (HierarchicalPropertiesException e) {
        throw new MessagingException("Error requesting certificate.", e);
    } catch (IOException e) {
        throw new MessagingException("Error requesting certificate.", e);
    } catch (CAException e) {
        throw new MessagingException("Error requesting certificate.", e);
    }
}

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

private void checkSignature(SMIMESignedInspector signedInspector,
        Collection<X509Certificate> usersRelayCertificates) throws MessagingException, RelayException {
    Collection<X509Certificate> certificates = null;

    try {/*from w  ww .  j ava2s . co  m*/
        certificates = signedInspector.getCertificates();
    } catch (CryptoMessageSyntaxException e) {
        logger.error("Error getting certificates from signed message.", e);
    }

    List<SignerInfo> signers;

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

    boolean relayingAllowed = false;

    try {
        /*
         * Validate the signature and check if the signing certificate can be used for relaying
         */
        for (int signerIndex = 0; signerIndex < signers.size(); signerIndex++) {
            SignerInfo signer = signers.get(signerIndex);

            SignerIdentifier signerId = signer.getSignerId();

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

            certSelector = signerId.getSelector();

            /* 
             * 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 check 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 (!isValid(signingCertificate)) {
                    continue;
                }

                /*
                 * Check if the message was signed by the signer and not tampered
                 */
                verifySignature(signer, signingCertificate);

                /*
                 * Now see if the signingCertificate can be used for relaying. We do not need to check 
                 * whether the usersRelayCertificates are valid because we have already checked the 
                 * signingCertificate for validity (see check above)
                 */
                if (usersRelayCertificates.contains(signingCertificate)) {
                    relayingAllowed = true;

                    break;
                }
            } else {
                logger.warn("Signing certificate could not be found.");
            }
        }

        if (!relayingAllowed) {
            throw new RelayException(RelayStep.RELAYING_NOT_ALLOWED, NO_VALID_CERTIFICATES);
        }
    } catch (IOException e) {
        throw new RelayException("Error checking the signature", e);
    }
}

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

protected void onHandleUserEvent(User user) throws MessagingException {
    ActivationContext passwordActivationContext = getActivationContext().get(ACTIVATION_CONTEXT_KEY,
            ActivationContext.class);

    Check.notNull(passwordActivationContext, "passwordActivationContext");

    UserProperties userProperties = user.getUserPreferences().getProperties();

    String passwordID = generatePasswordID();

    String password;//  ww  w.j  a v  a  2  s.co  m
    int passwordLength;

    try {
        passwordLength = getPasswordLength(userProperties);

        password = generatePassword(user, passwordLength, passwordID);
    } catch (HierarchicalPropertiesException e) {
        throw new MessagingException("Error generating password", e);
    }

    getLogger().debug("PasswordID for user '" + user.getEmail() + "': " + passwordID);

    try {
        userProperties.setPassword(password);
        userProperties.setPasswordID(passwordID);
    } catch (HierarchicalPropertiesException e) {
        throw new MessagingException("Unable to set password for user " + user.getEmail(), e);
    }

    PasswordContainer passwordContainer;

    try {
        passwordContainer = new PasswordContainer(password, passwordID);

        passwordContainer.setPasswordLength(passwordLength);
    } catch (EncryptorException e) {
        throw new MessagingException("Unable to create PasswordContainer.", e);
    }

    passwordActivationContext.getPasswords().put(user.getEmail(), passwordContainer);
    passwordActivationContext.getUsers().add(user);
}

From source file:mitm.common.mail.BodyPartUtils.java

/**
 * Searches for an embedded RFC822 messages. Returns the first embedded RFC822 it finds.
 * Only one level deep is searched./*from  ww  w  .j av a2  s.com*/
 *  
 * Returns null if there are no embedded message.
 */
public static MimeMessage searchForRFC822(MimeMessage message) throws MessagingException, IOException {
    /*
     * Fast fail. Only multipart mixed messages are supported. 
     */
    if (!message.isMimeType("multipart/mixed")) {
        return null;
    }

    Multipart mp;

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

    MimeMessage embeddedMessage = null;

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

        if (part.isMimeType("message/rfc822")) {
            embeddedMessage = BodyPartUtils.extractFromRFC822(part);

            break;
        }
    }

    return embeddedMessage;
}

From source file:mitm.common.mail.filter.UnsupportedFormatStripper.java

/**
 * Strips unsupported attachments. Returns a new message if HTML part(s) or
 * attachments have been removed and null if the message was not modified (ie
 * there were no unsuported formats to remove)
 *//* w  ww.  ja  v  a2  s  . c o m*/
public MimeMessage strip(MimeMessage message) throws MessagingException {
    MimeMessage newMessage = null;

    PartsContext context = new PartsContext();

    try {
        scanPart(message, context, 0);

        if (context.isModified() && context.getParts().size() > 0) {
            newMessage = buildMessage(message, context);
        }

        return newMessage;
    } catch (IOException e) {
        throw new MessagingException("Error stripping unsupported formats.", e);
    }
}

From source file:com.zimbra.cs.mailbox.MailboxTestUtil.java

public static ParsedMessage generateMessageWithAttachment(String subject) throws Exception {
    MimeMessage mm = new Mime.FixedMimeMessage(JMSession.getSession());
    mm.setHeader("From", "Vera Oliphant <oli@example.com>");
    mm.setHeader("To", "Jimmy Dean <jdean@example.com>");
    mm.setHeader("Subject", subject);
    mm.setText("Good as gold");
    MimeMultipart multi = new ZMimeMultipart("mixed");
    ContentDisposition cdisp = new ContentDisposition(Part.ATTACHMENT);
    cdisp.setParameter("filename", "fun.txt");

    ZMimeBodyPart bp = new ZMimeBodyPart();
    // MimeBodyPart.setDataHandler() invalidates Content-Type and CTE if there is any, so make sure
    // it gets called before setting Content-Type and CTE headers.
    try {//  ww  w.  jav a 2s .  c o m
        bp.setDataHandler(new DataHandler(new ByteArrayDataSource("Feeling attached.", "text/plain")));
    } catch (IOException e) {
        throw new MessagingException("could not generate mime part content", e);
    }
    bp.addHeader("Content-Disposition", cdisp.toString());
    bp.addHeader("Content-Type", "text/plain");
    bp.addHeader("Content-Transfer-Encoding", MimeConstants.ET_8BIT);
    multi.addBodyPart(bp);

    mm.setContent(multi);
    mm.saveChanges();

    return new ParsedMessage(mm, false);
}