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:EmailJndiServlet.java

private void sendMessage(String to, String from, String subject, String bodyContent) throws Exception {

    Message mailMsg = null;//from w w w  .  j av  a 2  s  .c o m

    synchronized (mailSession) {

        mailMsg = new MimeMessage(mailSession);//a new email message
    }

    InternetAddress[] addresses = null;

    try {

        if (to != null) {

            //throws 'AddressException' if the 'to' email address
            //violates RFC822 syntax
            addresses = InternetAddress.parse(to, false);

            mailMsg.setRecipients(Message.RecipientType.TO, addresses);

        } else {

            throw new MessagingException("The mail message requires a 'To' address.");

        }

        if (from != null)
            mailMsg.setFrom(new InternetAddress(from));

        if (subject != null)
            mailMsg.setSubject(subject);

        if (bodyContent != null)
            mailMsg.setText(bodyContent);

        //Finally, send the mail message; throws a 'SendFailedException' 
        //if any of the message's recipients have an invalid adress
        Transport.send(mailMsg);

    } catch (Exception exc) {

        throw exc;
    }
}

From source file:MSMessage.java

/**
 * Constructor that converts a MimeMessage object into a MSMessage.
 * //from   w  ww. j ava  2 s .  co  m
 * @exception   MessagingException if the given MimeMessage
 *          is not a non-MIME MS message, or if an
 *          IOException occurs when accessing the given
 *          MimeMessage object
 */
public MSMessage(Session session, MimeMessage msg) throws MessagingException {
    super(session);

    if (!isMSMessage(msg)) // sanity check
        throw new MessagingException("Not an MS message");

    class FastByteArrayOutputStream extends ByteArrayOutputStream {
        ByteArrayInputStream toByteArrayInputStream() {
            return new ByteArrayInputStream(buf, 0, count);
        }
    }

    // extract the bytes of the given message
    // ByteArrayOutputStream bos = new ByteArrayOutputStream();
    FastByteArrayOutputStream bos = new FastByteArrayOutputStream();
    try {
        msg.writeTo(bos);
    } catch (IOException ioex) {
        throw new MessagingException("IOException", ioex);
    } catch (Exception ex) {
        throw new MessagingException("Exception", ex);
    }
    //parse(new ByteArrayInputStream(bos.toByteArray()));
    parse(bos.toByteArrayInputStream());
}

From source file:com.silverpeas.mailinglist.service.job.TestZimbraConnection.java

@Test
public void testOpenImapConnection() {
    URL url = this.getClass().getClassLoader().getResource("truststore.jks");
    String path = url.getPath();/*from ww  w  .  j  a  va  2 s .  c om*/
    System.setProperty("javax.net.ssl.trustStore", path);
    System.setProperty("javax.net.ssl.trustStorePassword", "changeit");
    Store mailAccount = null;
    Folder inbox = null;
    Session mailSession = Session.getInstance(System.getProperties());
    try {
        mailSession.setDebug(true);
        mailAccount = mailSession.getStore(props.getProperty("mail.server.protocol"));
        mailAccount.connect(props.getProperty("mail.server.host"),
                Integer.parseInt(props.getProperty("mail.server.port")), props.getProperty("mail.server.login"),
                props.getProperty("mail.server.password"));
        inbox = mailAccount.getFolder("INBOX");
        if (inbox == null) {
            throw new MessagingException("No POP3 INBOX");
        }
        // -- Open the folder for read write --
        inbox.open(Folder.READ_WRITE);

        // -- Get the message wrappers and process them --
        Message[] msgs = inbox.getMessages();
        FetchProfile profile = new FetchProfile();
        profile.add(FetchProfile.Item.FLAGS);
        inbox.fetch(msgs, profile);
    } catch (MessagingException mex) {
        SilverTrace.error("mailingList", "MessageChecker.checkNewMessages", "mail.processing.error", mex);
    } catch (Exception mex) {
        SilverTrace.error("mailingList", "MessageChecker.checkNewMessages", "mail.processing.error", mex);
    } finally {
        // -- Close down nicely --
        try {
            if (inbox != null) {
                inbox.close(false);
            }
            if (mailAccount != null) {
                mailAccount.close();
            }
        } catch (Exception ex2) {
            SilverTrace.error("mailingList", "MessageChecker.checkNewMessages", "mail.processing.error", ex2);
        }
    }

}

From source file:com.silverpeas.mailinglist.service.job.TestYahooMailConnection.java

@Test
public void testOpenImapConnection() throws Exception {
    Store mailAccount = null;/* w  ww.j  a  v  a  2 s.com*/
    Folder inbox = null;
    Session mailSession = Session.getInstance(System.getProperties());
    try {
        mailSession.setDebug(true);
        mailAccount = mailSession.getStore(props.getProperty("mail.server.protocol"));
        mailAccount.connect(props.getProperty("mail.server.host"),
                Integer.parseInt(props.getProperty("mail.server.port")), props.getProperty("mail.server.login"),
                props.getProperty("mail.server.password"));
        inbox = mailAccount.getFolder("INBOX");
        if (inbox == null) {
            throw new MessagingException("No POP3 INBOX");
        }
        // -- Open the folder for read write --
        inbox.open(Folder.READ_WRITE);

        // -- Get the message wrappers and process them --
        javax.mail.Message[] msgs = inbox.getMessages();
        FetchProfile profile = new FetchProfile();
        profile.add(FetchProfile.Item.FLAGS);
        inbox.fetch(msgs, profile);
        MailProcessor processor = new MailProcessor();
        MessageListener mailingList = mock(MessageListener.class);
        when(mailingList.checkSender(anyString())).thenReturn(Boolean.TRUE);
        when(mailingList.getComponentId()).thenReturn("mailingList38");
        MessageEvent event = new MessageEvent();
        for (javax.mail.Message message : msgs) {
            processor.prepareMessage((MimeMessage) message, mailingList, event);
        }
        assertThat(event.getMessages(), is(notNullValue()));
        assertThat(event.getMessages().size(), is(msgs.length));
        for (com.silverpeas.mailinglist.service.model.beans.Message message : event.getMessages()) {
            assertThat(message, is(notNullValue()));
            assertThat(message.getMessageId(), is(notNullValue()));
        }
    } finally {
        // -- Close down nicely --
        if (inbox != null) {
            inbox.close(false);
        }
        if (mailAccount != null) {
            mailAccount.close();
        }
    }
}

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

/**
 * Initialize the mailet./*  www  .  j a  v  a2s  .com*/
 */
public void init() throws MessagingException {

    passThrough = (getInitParameter("passThrough", "true").compareToIgnoreCase("true") == 0);
    String targetUrl = getInitParameter("url");
    parameterKey = getInitParameter("parameterKey");
    parameterValue = getInitParameter("parameterValue");

    // Check if needed config values are used
    if (targetUrl == null || targetUrl.equals("")) {
        throw new MessagingException("Please configure a targetUrl (\"url\")");
    } else {
        try {
            // targetUrl = targetUrl + ( targetUrl.contains("?") ? "&" :
            // "?") + parameterKey + "=" + parameterValue;
            url = new URL(targetUrl).toExternalForm();
        } catch (MalformedURLException e) {
            throw new MessagingException("Unable to contruct URL object from url");
        }
    }

    // record the result
    log("I will attempt to deliver serialised messages to " + targetUrl + ". "
            + (((parameterKey == null) || (parameterKey.length() < 1))
                    ? "I will not add any fields to the post. "
                    : "I will prepend: " + parameterKey + "=" + parameterValue + ". ")
            + (passThrough ? "Messages will pass through." : "Messages will be ghosted."));
}

From source file:MSMultipartDataSource.java

public MSMultipartDataSource(MimePart part, byte[] content) throws MessagingException {
    super(part);//from www .ja v a2 s .co  m
    //parts = new ArrayList<MSBodyPart>();
    parts = new ArrayList();

    /*
     * Parse the text of the message to find the attachments.
     *
     * Currently we just look for the lines that mark the
     * begin and end of uuencoded data, but this can be
     * fooled by similar text in the message body.  Instead,
     * we could use the Encoding header, which indicates how
     * many lines are in each body part.  For example:
     *
     * Encoding: 41 TEXT, 38 UUENCODE, 3155 UUENCODE, 1096 UUENCODE
     *
     * Similarly, we could get the filenames of the attachments
     * from the X-MS-Attachment headers.  For example:
     *
     * X-MS-Attachment: ATT00000.htx 0 00-00-1980 00:00
     * X-MS-Attachment: Serengeti 2GG.mpp 0 00-00-1980 00:00
     * X-MS-Attachment: project team update 031298.doc 0 00-00-1980 00:00
     *
     * (Note that there might be unquoted spaces in the filename.)
     */
    int pos = startsWith(content, 0, "begin");
    if (pos == -1)
        throw new MessagingException("invalid multipart");

    if (pos > 0) // we have an unencoded main body part
        parts.add(new MSBodyPart(content, 0, pos, "inline", "7bit"));
    else // no main body part
        pos = 0;

    // now collect all the uuencoded individual body parts
    int start;
    for (;;) {
        start = startsWith(content, pos, "begin");
        if (start == -1)
            break;
        pos = startsWith(content, start, "end");
        if (pos == -1)
            break;
        pos += 3; // skip to the end of "end"
        parts.add(new MSBodyPart(content, start, pos, "attachment", "uuencode"));
    }
}

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

/**
 * Initialize the mailet.// w w w.ja v a  2  s .c o  m
 */
public void init() throws MessagingException {

    passThrough = (getInitParameter("passThrough", "true").compareToIgnoreCase("true") == 0);
    String targetUrl = getInitParameter("url");
    parameterKey = getInitParameter("parameterKey");
    parameterValue = getInitParameter("parameterValue");
    String m = getInitParameter("MessageKeyName");
    if (m != null) {
        messageKeyName = m;
    }

    // Check if needed config values are used
    if (targetUrl == null || targetUrl.equals("")) {
        throw new MessagingException("Please configure a targetUrl (\"url\")");
    } else {
        try {
            // targetUrl = targetUrl + ( targetUrl.contains("?") ? "&" :
            // "?") + parameterKey + "=" + parameterValue;
            url = new URL(targetUrl).toExternalForm();
        } catch (MalformedURLException e) {
            throw new MessagingException("Unable to contruct URL object from url");
        }
    }

    // record the result
    log("I will attempt to deliver serialised messages to " + targetUrl + " as " + messageKeyName + ". "
            + (parameterKey == null || parameterKey.length() < 2 ? "I will not add any fields to the post. "
                    : "I will prepend: " + parameterKey + "=" + parameterValue + ". ")
            + (passThrough ? "Messages will pass through." : "Messages will be ghosted."));
}

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

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

    keyProperty = getInitParameter("keyProperty");

    if (keyProperty == null) {
        throw new MessagingException("keyProperty is missing.");
    }//from  w w  w  .j a v  a  2 s  . c  o  m

    sessionManager = SystemServices.getSessionManager();

    userWorkflow = SystemServices.getUserWorkflow();

    messageOriginatorIdentifier = SystemServices.getMessageOriginatorIdentifier();

    actionExecutor = DatabaseActionExecutorBuilder.createDatabaseActionExecutor(sessionManager);
}

From source file:com.canoo.webtest.plugins.emailtest.EmailMessageContentFilter.java

private void extractMultiPartMessage(final Multipart parts, final int partIndex) throws MessagingException {
    try {//from   w  w w  .j av a2s .  c o  m
        if (partIndex >= parts.getCount()) {
            throw new StepFailedException("PartIndex too large.", this);
        }
        final BodyPart part = parts.getBodyPart(partIndex);
        final String contentType = part.getContentType();
        if (!StringUtils.isEmpty(getContentType()) && !contentType.equals(getContentType())) {
            throw new MessagingException("Actual contentType of '" + contentType
                    + "' did not match expected contentType of '" + fContentType + "'");
        }
        final String disp = part.getDisposition();
        final String filename = part.getFileName();
        final InputStream inputStream = part.getInputStream();
        if (Part.ATTACHMENT.equals(disp)) {
            fFilename = filename;
        } else {
            fFilename = getClass().getName();
        }
        ContextHelper.defineAsCurrentResponse(getContext(), IOUtils.toString(inputStream), contentType,
                "http://" + fFilename);
    } catch (IOException e) {
        throw new MessagingException("Error extracting part: " + e.getMessage());
    }
}

From source file:dk.dma.msinm.common.mail.AttachmentMailPart.java

/**
 * Instantiates an attachment mail part from a content byte array
 * @param content the content byte array
 * @param contentType the content type//from w  ww.  j  a  v  a 2  s .  c om
 * @param name the name of the attachment.
 */
public static AttachmentMailPart fromContent(byte[] content, String contentType, String name)
        throws MessagingException {
    // Check that the content is a valid byte array
    if (content == null || content.length == 0) {
        throw new MessagingException("Invalid empty content byte array");
    }
    if (contentType == null || contentType.length() == 0) {
        contentType = "application/octet-stream";
    }
    if (StringUtils.isBlank(name)) {
        name = "unknown";
    }

    // Instantiate a mail attachment
    AttachmentMailPart a = new AttachmentMailPart(name);
    a.content = content;
    a.contentType = contentType;
    return a;
}