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.synyx.greetingcard.mail.OpenCmsMailService.java

public void sendMultipartMail(MessageConfig config, DataSource ds, String filename) throws MessagingException {
    log.debug("Sending multipart message " + config);

    Session session = getSession();//from w  w  w . j av  a2  s . co  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(ds));
    messageBodyPart.setFileName(filename);
    multipart.addBodyPart(messageBodyPart);

    final MimeMessage message = new MimeMessage(session);
    message.setContent(multipart);
    try {
        message.setFrom(new InternetAddress(config.getFrom(), config.getFromName()));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(config.getTo(), config.getToName()));
    } 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:com.springstudy.utils.email.MimeMailService.java

/**
 * Freemarker?html?.//w  w w .  jav a 2  s  . c  o  m
 */
private String generateContent(String template, Map context) throws MessagingException {
    try {
        Template template1 = freeMarkerConfigurer.getConfiguration().getTemplate(template, DEFAULT_ENCODING);
        return FreeMarkerTemplateUtils.processTemplateIntoString(template1, context);
    } catch (IOException e) {
        logger.error("?, FreeMarker??", e);
        throw new MessagingException("FreeMarker??", e);
    } catch (TemplateException e) {
        logger.error("?, FreeMarker?", e);
        throw new MessagingException("FreeMarker?", e);
    }
}

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

protected static PublicKey parseKey(String pkcs8) throws MessagingException {
    PublicKey key = null;// w  ww . j  ava2  s .  c  om

    pkcs8 = StringUtils.trimToNull(pkcs8);

    if (pkcs8 != null) {
        PEMReader pem = new PEMReader(new StringReader(pkcs8));

        Object o;

        try {
            o = pem.readObject();
        } catch (IOException e) {
            throw new MessagingException("Unable to read PEM encoded private key", e);
        }

        if (o instanceof PublicKey) {
            key = (PublicKey) o;
        } else if (o instanceof KeyPair) {
            key = ((KeyPair) o).getPublic();
        } else if (o == null) {
            throw new MessagingException("The PEM encoded blob did not return any object.");
        } else {
            throw new MessagingException("The PEM input is not a PublicKey or KeyPair but a " + o.getClass());
        }
    }

    return key;
}

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

protected void onHandleUserEvent(User user, MutableObject pemKeyPairHolder) throws MessagingException {
    try {//  w  w w  .  j a va 2s.  c om
        pemKeyPairHolder.setValue(user.getUserPreferences().getProperties().getProperty(keyProperty, false));
    } catch (HierarchicalPropertiesException e) {
        throw new MessagingException("Error reading DKIM key pair.", e);
    }
}

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

protected boolean hasMatch(User user) throws MessagingException {
    /*//from w ww.j a v a  2 s  .  co  m
     * Return true if user does not have a portal password
     */
    try {
        return (StringUtils
                .isNotEmpty(user.getUserPreferences().getProperties().getPortalProperties().getPassword()));
    } catch (HierarchicalPropertiesException e) {
        throw new MessagingException("Exception getting portal password.", e);
    }
}

From source file:MSMessage.java

protected void parse(InputStream is) throws MessagingException {
    // Create a buffered input stream for efficiency
    if (!(is instanceof ByteArrayInputStream) && !(is instanceof BufferedInputStream))
        is = new BufferedInputStream(is);

    // Load headerstore
    headers.load(is);/*from w w w .j  a  va2s  . c o  m*/

    /*
     * Load the content into a byte[].
     * This byte[] is shared among the bodyparts.
     */
    try {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        int b;
        // XXX - room for performance improvement
        while ((b = is.read()) != -1)
            bos.write(b);
        content = bos.toByteArray();
    } catch (IOException ioex) {
        throw new MessagingException("IOException", ioex);
    }

    /*
     * Check whether this is multipart.
     */
    boolean isMulti = false;
    // check for presence of X-MS-Attachment header
    String[] att = getHeader("X-MS-Attachment");
    if (att != null && att.length > 0)
        isMulti = true;
    else {
        /*
         * Fall back to scanning the content.
         * We scan the content until we find a sequence that looks
         * like the start of a uuencoded block, i.e., "<newline>begin".
         * If found, we claim that this is a multipart message.
         */
        for (int i = 0; i < content.length; i++) {
            int b = content[i] & 0xff; // mask higher byte
            if (b == '\r' || b == '\n') {
                // start of a new line
                if ((i + 5) < content.length) {
                    // can there be a "begin" now?
                    String s = toString(content, i + 1, i + 6);
                    if (s.equalsIgnoreCase("begin")) {
                        isMulti = true;
                        break;
                    }
                }
            }
        }
    }

    if (isMulti) {
        type = "multipart/mixed";
        dh = new DataHandler(new MSMultipartDataSource(this, content));
    } else {
        type = "text/plain"; // charset = ?
        dh = new DataHandler(new MimePartDataSource(this));
    }

    modified = false;
}

From source file:ch.algotrader.util.mail.EmailTransformer.java

/**
 * Parses any {@link Multipart} instances that contains attachments
 *
 * Will create the respective {@link EmailFragment}s representing those attachments.
 * @throws MessagingException//from   ww w  .j  ava 2 s  . co  m
 */
public void handleMultipart(Multipart multipart, List<EmailFragment> emailFragments) throws MessagingException {

    final int count = multipart.getCount();

    for (int i = 0; i < count; i++) {

        BodyPart bodyPart = multipart.getBodyPart(i);
        String filename = bodyPart.getFileName();
        String disposition = bodyPart.getDisposition();

        if (filename == null && bodyPart instanceof MimeBodyPart) {
            filename = ((MimeBodyPart) bodyPart).getContentID();
        }

        if (disposition == null) {

            //ignore message body

        } else if (disposition.equalsIgnoreCase(Part.ATTACHMENT) || disposition.equalsIgnoreCase(Part.INLINE)) {

            try {
                try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
                        BufferedInputStream bis = new BufferedInputStream(bodyPart.getInputStream())) {

                    IOUtils.copy(bis, bos);

                    emailFragments.add(new EmailFragment(filename, bos.toByteArray()));

                    if (LOGGER.isInfoEnabled()) {
                        LOGGER.info(String.format("processing file: %s", new Object[] { filename }));
                    }

                }

            } catch (IOException e) {
                throw new MessagingException("error processing streams", e);
            }

        } else {
            throw new MessagingException("unkown disposition " + disposition);
        }
    }
}

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

@Override
protected byte[] getSecret(Mail mail) throws MessagingException {
    try {//w  w  w .  j  av a2  s. c o  m
        return actionExecutor.executeTransaction(new DatabaseAction<byte[]>() {
            @Override
            public byte[] doAction(Session session) throws DatabaseException {
                Session previousSession = sessionManager.getSession();

                sessionManager.setSession(session);

                try {
                    return getSecretTransacted();
                } finally {
                    sessionManager.setSession(previousSession);
                }
            }
        }, ACTION_RETRIES);
    } catch (DatabaseException e) {
        throw new MessagingException("Error in handleRecipientsAction.", e);
    } catch (HibernateException e) {
        throw new MessagingException("HibernateException.", e);
    }
}

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

protected boolean hasMatch(User user) throws MessagingException {
    /*/*from   www  .  j a va 2 s .  co  m*/
     * Return true if user locality match.
     */
    try {
        return (user.getUserPreferences().getProperties().getUserLocality() == userLocality);
    } catch (HierarchicalPropertiesException e) {
        throw new MessagingException("Exception getting userLocality.", e);
    }
}

From source file:mitm.application.djigzo.ca.PFXMailBuilder.java

private void replacePFX(MimeMessage message) throws MessagingException {
    Multipart mp;//ww w . j  a v  a 2  s.co  m

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

    BodyPart pfxPart = null;

    /*
     * Fallback in case the template does not contain a DjigzoHeader.MARKER
     */
    BodyPart octetStreamPart = null;

    /*
     * Try to find the first attachment with X-Djigzo-Marker attachment header which should be the attachment
     * we should replace (we should replace the content and keep the headers)
     */
    for (int i = 0; i < mp.getCount(); i++) {
        BodyPart part = mp.getBodyPart(i);

        if (ArrayUtils.contains(part.getHeader(DjigzoHeader.MARKER), DjigzoHeader.ATTACHMENT_MARKER_VALUE)) {
            pfxPart = part;

            break;
        }

        /*
         * Fallback scanning for octet-stream in case the template does not contain a DjigzoHeader.MARKER
         */
        if (part.isMimeType("application/octet-stream")) {
            octetStreamPart = part;
        }
    }

    if (pfxPart == null) {
        if (octetStreamPart != null) {
            logger.info("Marker not found. Using ocet-stream instead.");

            /*
             * Use the octet-stream part
             */
            pfxPart = octetStreamPart;
        } else {
            throw new MessagingException("Unable to find the attachment part in the template.");
        }
    }

    pfxPart.setDataHandler(new DataHandler(new ByteArrayDataSource(pfx, "application/octet-stream")));
}