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) 

Source Link

Document

Constructs a MessagingException with the specified detail message.

Usage

From source file:org.apache.james.transport.mailets.SMIMEDecrypt.java

public void init() throws MessagingException {
    super.init();

    MailetConfig config = getMailetConfig();

    String privateStoreType = config.getInitParameter("keyStoreType");

    String privateStoreFile = config.getInitParameter("keyStoreFileName");
    if (privateStoreFile == null)
        throw new MessagingException("No keyStoreFileName specified");

    String privateStorePass = config.getInitParameter("keyStorePassword");

    String keyAlias = config.getInitParameter("keyAlias");
    String keyPass = config.getInitParameter("keyAliasPassword");

    String mailAttributeConf = config.getInitParameter("mailAttribute");
    if (mailAttributeConf != null)
        mailAttribute = mailAttributeConf;

    try {/* ww  w  .jav a2  s .co  m*/
        keyHolder = new SMIMEKeyHolder(privateStoreFile, privateStorePass, keyAlias, keyPass, privateStoreType);
    } catch (IOException e) {
        throw new MessagingException("Error loading keystore", e);
    } catch (GeneralSecurityException e) {
        throw new MessagingException("Error loading keystore", e);
    }

    certificateHolder = from(keyHolder.getCertificate());
}

From source file:org.apache.jmeter.assertions.SMIMEAssertion.java

/**
 * extracts a MIME message from the SampleResult
 *///  w ww  . ja v a2 s.c  o m
private static MimeMessage getMessageFromResponse(SampleResult response, int messageNumber)
        throws MessagingException {
    SampleResult[] subResults = response.getSubResults();

    if (messageNumber >= subResults.length || messageNumber < 0) {
        throw new MessagingException("Message number not present in results: " + messageNumber);
    }

    final SampleResult sampleResult = subResults[messageNumber];
    if (log.isDebugEnabled()) {
        log.debug("Bytes: " + sampleResult.getBytes() + " CT: " + sampleResult.getContentType());
    }
    byte[] data = sampleResult.getResponseData();
    Session session = Session.getDefaultInstance(new Properties());
    MimeMessage msg = new MimeMessage(session, new ByteArrayInputStream(data));

    log.debug("msg.getSize() = " + msg.getSize());
    return msg;
}

From source file:org.apache.jmeter.protocol.mail.sampler.MailFileFolder.java

@Override
public void appendMessages(Message[] messages) throws MessagingException {
    throw new MessagingException("Not supported");
}

From source file:org.apache.jmeter.protocol.mail.sampler.MailFileFolder.java

@Override
public void open(int mode) throws MessagingException {
    if (mode != READ_ONLY) {
        throw new MessagingException("Implementation only supports read-only access");
    }/*w w  w  .  ja v  a  2  s .  c om*/
    this.mode = mode;
    isOpen = true;
}

From source file:org.apache.mailet.base.GenericMailet.java

/**
 * Utility method: Checks if there are unallowed init parameters specified in the 
 * configuration file against the String[] allowedInitParameters.
 * @param allowedArray array of strings containing the allowed parameter names
 * @throws MessagingException if an unknown parameter name is found
 *//*  w  w w . j a v a 2 s  .c  om*/
protected final void checkInitParameters(String[] allowedArray) throws MessagingException {
    // if null then no check is requested
    if (allowedArray == null) {
        return;
    }

    Collection<String> allowed = new HashSet<String>();
    Collection<String> bad = new ArrayList<String>();

    Collections.addAll(allowed, allowedArray);

    Iterator<String> iterator = getInitParameterNames();
    while (iterator.hasNext()) {
        String parameter = iterator.next();
        if (!allowed.contains(parameter)) {
            bad.add(parameter);
        }
    }

    if (bad.size() > 0) {
        throw new MessagingException("Unexpected init parameters found: "
                + org.apache.mailet.base.StringUtils.arrayToString(bad.toArray()));
    }
}

From source file:org.apache.nifi.processors.email.ExtractEmailAttachments.java

@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) {
    final ComponentLog logger = getLogger();
    final FlowFile originalFlowFile = session.get();
    if (originalFlowFile == null) {
        return;/*  ww  w  .  j  av a2  s  . c  o  m*/
    }
    final List<FlowFile> attachmentsList = new ArrayList<>();
    final List<FlowFile> invalidFlowFilesList = new ArrayList<>();
    final List<FlowFile> originalFlowFilesList = new ArrayList<>();

    session.read(originalFlowFile, new InputStreamCallback() {
        @Override
        public void process(final InputStream rawIn) throws IOException {
            try (final InputStream in = new BufferedInputStream(rawIn)) {
                Properties props = new Properties();
                Session mailSession = Session.getDefaultInstance(props, null);
                MimeMessage originalMessage = new MimeMessage(mailSession, in);
                MimeMessageParser parser = new MimeMessageParser(originalMessage).parse();
                // RFC-2822 determines that a message must have a "From:" header
                // if a message lacks the field, it is flagged as invalid
                Address[] from = originalMessage.getFrom();
                Date sentDate = originalMessage.getSentDate();
                if (from == null || sentDate == null) {
                    // Throws MessageException due to lack of minimum required headers
                    throw new MessagingException("Message failed RFC2822 validation");
                }
                originalFlowFilesList.add(originalFlowFile);
                if (parser.hasAttachments()) {
                    final String originalFlowFileName = originalFlowFile
                            .getAttribute(CoreAttributes.FILENAME.key());
                    try {
                        for (final DataSource data : parser.getAttachmentList()) {
                            FlowFile split = session.create(originalFlowFile);
                            final Map<String, String> attributes = new HashMap<>();
                            if (StringUtils.isNotBlank(data.getName())) {
                                attributes.put(CoreAttributes.FILENAME.key(), data.getName());
                            }
                            if (StringUtils.isNotBlank(data.getContentType())) {
                                attributes.put(CoreAttributes.MIME_TYPE.key(), data.getContentType());
                            }
                            String parentUuid = originalFlowFile.getAttribute(CoreAttributes.UUID.key());
                            attributes.put(ATTACHMENT_ORIGINAL_UUID, parentUuid);
                            attributes.put(ATTACHMENT_ORIGINAL_FILENAME, originalFlowFileName);
                            split = session.append(split, new OutputStreamCallback() {
                                @Override
                                public void process(OutputStream out) throws IOException {
                                    IOUtils.copy(data.getInputStream(), out);
                                }
                            });
                            split = session.putAllAttributes(split, attributes);
                            attachmentsList.add(split);
                        }
                    } catch (FlowFileHandlingException e) {
                        // Something went wrong
                        // Removing splits that may have been created
                        session.remove(attachmentsList);
                        // Removing the original flow from its list
                        originalFlowFilesList.remove(originalFlowFile);
                        logger.error(
                                "Flowfile {} triggered error {} while processing message removing generated FlowFiles from sessions",
                                new Object[] { originalFlowFile, e });
                        invalidFlowFilesList.add(originalFlowFile);
                    }
                }
            } catch (Exception e) {
                // Another error hit...
                // Removing the original flow from its list
                originalFlowFilesList.remove(originalFlowFile);
                logger.error("Could not parse the flowfile {} as an email, treating as failure",
                        new Object[] { originalFlowFile, e });
                // Message is invalid or triggered an error during parsing
                invalidFlowFilesList.add(originalFlowFile);
            }
        }
    });

    session.transfer(attachmentsList, REL_ATTACHMENTS);

    // As per above code, originalFlowfile may be routed to invalid or
    // original depending on RFC2822 compliance.
    session.transfer(invalidFlowFilesList, REL_FAILURE);
    session.transfer(originalFlowFilesList, REL_ORIGINAL);

    if (attachmentsList.size() > 10) {
        logger.info("Split {} into {} files", new Object[] { originalFlowFile, attachmentsList.size() });
    } else if (attachmentsList.size() > 1) {
        logger.info("Split {} into {} files: {}",
                new Object[] { originalFlowFile, attachmentsList.size(), attachmentsList });
    }
}

From source file:org.apache.nifi.processors.email.ExtractEmailHeaders.java

@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) {
    final ComponentLog logger = getLogger();

    final List<FlowFile> invalidFlowFilesList = new ArrayList<>();
    final List<FlowFile> processedFlowFilesList = new ArrayList<>();

    final FlowFile originalFlowFile = session.get();
    if (originalFlowFile == null) {
        return;/*from w w  w .j  a  v a  2  s.c  om*/
    }

    final List<String> capturedHeadersList = Arrays
            .asList(context.getProperty(CAPTURED_HEADERS).getValue().toLowerCase().split(":"));

    final Map<String, String> attributes = new HashMap<>();
    session.read(originalFlowFile, new InputStreamCallback() {
        @Override
        public void process(final InputStream rawIn) throws IOException {
            try (final InputStream in = new BufferedInputStream(rawIn)) {
                Properties props = new Properties();
                Session mailSession = Session.getDefaultInstance(props, null);
                MimeMessage originalMessage = new MimeMessage(mailSession, in);
                MimeMessageParser parser = new MimeMessageParser(originalMessage).parse();
                // RFC-2822 determines that a message must have a "From:" header
                // if a message lacks the field, it is flagged as invalid
                Address[] from = originalMessage.getFrom();
                Date sentDate = originalMessage.getSentDate();
                if (from == null || sentDate == null) {
                    // Throws MessageException due to lack of minimum required headers
                    throw new MessagingException("Message failed RFC2822 validation");
                } else if (capturedHeadersList.size() > 0) {
                    Enumeration headers = originalMessage.getAllHeaders();
                    while (headers.hasMoreElements()) {
                        Header header = (Header) headers.nextElement();
                        if (StringUtils.isNotEmpty(header.getValue())
                                && capturedHeadersList.contains(header.getName().toLowerCase())) {
                            attributes.put("email.headers." + header.getName().toLowerCase(),
                                    header.getValue());
                        }
                    }
                }
                if (Array.getLength(originalMessage.getAllRecipients()) > 0) {
                    for (int toCount = 0; toCount < ArrayUtils
                            .getLength(originalMessage.getRecipients(Message.RecipientType.TO)); toCount++) {
                        attributes.put(EMAIL_HEADER_TO + "." + toCount,
                                originalMessage.getRecipients(Message.RecipientType.TO)[toCount].toString());
                    }
                    for (int toCount = 0; toCount < ArrayUtils
                            .getLength(originalMessage.getRecipients(Message.RecipientType.BCC)); toCount++) {
                        attributes.put(EMAIL_HEADER_BCC + "." + toCount,
                                originalMessage.getRecipients(Message.RecipientType.BCC)[toCount].toString());
                    }
                    for (int toCount = 0; toCount < ArrayUtils
                            .getLength(originalMessage.getRecipients(Message.RecipientType.CC)); toCount++) {
                        attributes.put(EMAIL_HEADER_CC + "." + toCount,
                                originalMessage.getRecipients(Message.RecipientType.CC)[toCount].toString());
                    }
                }
                // Incredibly enough RFC-2822 specified From as a "mailbox-list" so an array I returned by getFrom
                for (int toCount = 0; toCount < ArrayUtils.getLength(originalMessage.getFrom()); toCount++) {
                    attributes.put(EMAIL_HEADER_FROM + "." + toCount,
                            originalMessage.getFrom()[toCount].toString());
                }
                if (StringUtils.isNotEmpty(originalMessage.getMessageID())) {
                    attributes.put(EMAIL_HEADER_MESSAGE_ID, originalMessage.getMessageID());
                }
                if (originalMessage.getReceivedDate() != null) {
                    attributes.put(EMAIL_HEADER_RECV_DATE, originalMessage.getReceivedDate().toString());
                }
                if (originalMessage.getSentDate() != null) {
                    attributes.put(EMAIL_HEADER_SENT_DATE, originalMessage.getSentDate().toString());
                }
                if (StringUtils.isNotEmpty(originalMessage.getSubject())) {
                    attributes.put(EMAIL_HEADER_SUBJECT, originalMessage.getSubject());
                }
                // Zeroes EMAIL_ATTACHMENT_COUNT
                attributes.put(EMAIL_ATTACHMENT_COUNT, "0");
                // But insert correct value if attachments are present
                if (parser.hasAttachments()) {
                    attributes.put(EMAIL_ATTACHMENT_COUNT, String.valueOf(parser.getAttachmentList().size()));
                }

            } catch (Exception e) {
                // Message is invalid or triggered an error during parsing
                attributes.clear();
                logger.error("Could not parse the flowfile {} as an email, treating as failure",
                        new Object[] { originalFlowFile, e });
                invalidFlowFilesList.add(originalFlowFile);
            }
        }
    });

    if (attributes.size() > 0) {
        FlowFile updatedFlowFile = session.putAllAttributes(originalFlowFile, attributes);
        logger.info("Extracted {} headers into {} file", new Object[] { attributes.size(), updatedFlowFile });
        processedFlowFilesList.add(updatedFlowFile);
    }

    session.transfer(processedFlowFilesList, REL_SUCCESS);
    session.transfer(invalidFlowFilesList, REL_FAILURE);

}

From source file:org.apache.nifi.processors.standard.TestPutEmail.java

@Test
public void testExceptionWhenSending() {
    // verifies that files are routed to failure when Transport.send() throws a MessagingException
    runner.setProperty(PutEmail.SMTP_HOSTNAME, "host-doesnt-exist123");
    runner.setProperty(PutEmail.FROM, "test@apache.org");
    runner.setProperty(PutEmail.TO, "test@apache.org");
    runner.setProperty(PutEmail.MESSAGE, "Message Body");

    processor.setException(new MessagingException("Forced failure from send()"));

    final Map<String, String> attributes = new HashMap<>();
    runner.enqueue("Some Text".getBytes(), attributes);

    runner.run();//w w w. jav a 2  s . co  m

    runner.assertQueueEmpty();
    runner.assertAllFlowFilesTransferred(PutEmail.REL_FAILURE);
    assertEquals("Expected an attempt to send a single message", 1, processor.getMessages().size());
}

From source file:org.b3log.solo.mail.local.MailSender.java

/**
 * Converts the specified message into a {@link javax.mail.Message
 * javax.mail.Message}./*from  w w  w. j a v a  2s  .c o m*/
 *
 * @param message the specified message
 * @return a {@link javax.mail.internet.MimeMessage}
 * @throws Exception if converts error
 */
public javax.mail.Message convert2JavaMailMsg(final Message message) throws Exception {
    if (null == message) {
        return null;
    }

    if (StringUtils.isBlank(message.getFrom())) {
        throw new MessagingException("Null from");
    }

    if (null == message.getRecipients() || message.getRecipients().isEmpty()) {
        throw new MessagingException("Null recipients");
    }

    final MimeMessage ret = new MimeMessage(getSession());

    ret.setFrom(new InternetAddress(message.getFrom()));
    final String subject = message.getSubject();

    ret.setSubject(MimeUtility.encodeText(subject != null ? subject : "", "UTF-8", "B"));
    final String htmlBody = message.getHtmlBody();

    ret.setContent(htmlBody != null ? htmlBody : "", "text/html;charset=UTF-8");
    ret.addRecipients(RecipientType.TO, transformRecipients(message.getRecipients()));

    return ret;
}

From source file:org.b3log.solo.mail.local.MailSender.java

/**
 * Transport recipients to InternetAddress array.
 *
 * @param recipients the set of all recipients
 * @return InternetAddress array of all recipients internetAddress
 * @throws MessagingException messagingException from javax.mail
 *///from ww w .  java  2s  . c o m
private InternetAddress[] transformRecipients(final Set<String> recipients) throws MessagingException {
    if (recipients.isEmpty()) {
        throw new MessagingException("recipients of mail should not be empty");
    }

    final InternetAddress[] ret = new InternetAddress[recipients.size()];
    int i = 0;

    for (String recipient : recipients) {
        ret[i] = new InternetAddress(recipient);
        i++;
    }

    return ret;
}