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:org.apache.james.server.core.MimeMessageWrapper.java

/**
 * Load the complete MimeMessage from the internal source.
 * /*ww  w.  j a  v  a 2 s  .c  o  m*/
 * @throws MessagingException
 *             if an error is encountered while loading the message
 */
public synchronized void loadMessage() throws MessagingException {
    if (messageParsed) {
        // Another thread has already loaded this message
    } else if (source != null) {
        sourceIn = null;
        try {
            sourceIn = source.getInputStream();

            parse(sourceIn);
            // TODO is it ok?
            saved = true;

        } catch (IOException ioe) {
            try {
                sourceIn.close();
            } catch (IOException e) {
                //ignore exception during close
            }
            sourceIn = null;
            throw new MessagingException("Unable to parse stream: " + ioe.getMessage(), ioe);
        }
    } else {
        throw new MessagingException("loadHeaders called for an unparsed message with no source");
    }
}

From source file:org.apache.james.server.core.MimeMessageWrapper.java

@Override
public synchronized InputStream getRawInputStream() throws MessagingException {
    if (!messageParsed && !isModified() && source != null) {
        InputStream is;/*from  w ww . java 2  s. co m*/
        try {
            is = source.getInputStream();
            // skip the headers.
            new MailHeaders(is);
            return is;
        } catch (IOException e) {
            throw new MessagingException("Unable to read the stream", e);
        }
    } else {
        return super.getRawInputStream();
    }
}

From source file:org.apache.james.transport.mailets.jsieve.delivery.SieveExecutor.java

private SieveFactory createFactory(Log log) throws MessagingException {
    try {//from   www .  j a  v  a  2 s .c  om
        final ConfigurationManager configurationManager = new ConfigurationManager();
        configurationManager.setLog(log);
        return configurationManager.build();
    } catch (SieveConfigurationException e) {
        throw new MessagingException("Failed to load standard Sieve configuration.", e);
    }
}

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

private X509CertificateHolder from(X509Certificate certificate) throws MessagingException {
    try {//from   w ww.  j  a v a2s.c o m
        return new X509CertificateHolder(certificate.getEncoded());
    } catch (CertificateEncodingException e) {
        throw new MessagingException("Error during the parsing of the certificate", e);
    } catch (IOException e) {
        throw new MessagingException("Error during the parsing of the certificate", e);
    }
}

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

/**
 * @see org.apache.mailet.Mailet#service(org.apache.mailet.Mail)
 *///w  w w. java 2s  .  c  o m
@SuppressWarnings("unchecked")
public void service(Mail mail) throws MessagingException {
    MimeMessage message = mail.getMessage();
    Part strippedMessage = null;
    log("Starting message decryption..");
    if (message.isMimeType("application/x-pkcs7-mime") || message.isMimeType("application/pkcs7-mime")) {
        try {
            SMIMEEnveloped env = new SMIMEEnveloped(message);
            RecipientInformationStore informationStore = env.getRecipientInfos();
            Collection<RecipientInformation> recipients = informationStore.getRecipients();
            for (RecipientInformation info : recipients) {
                RecipientId id = info.getRID();
                if (id.match(certificateHolder)) {
                    try {
                        JceKeyTransEnvelopedRecipient recipient = new JceKeyTransEnvelopedRecipient(
                                keyHolder.getPrivateKey());
                        // strippedMessage contains the decrypted message.
                        strippedMessage = SMIMEUtil.toMimeBodyPart(info.getContent(recipient));
                        log("Encrypted message decrypted");
                    } catch (Exception e) {
                        throw new MessagingException("Error during the decryption of the message", e);
                    }
                } else {
                    log("Found an encrypted message but it isn't encrypted for the supplied key");
                }
            }
        } catch (CMSException e) {
            throw new MessagingException("Error during the decryption of the message", e);
        }
    }

    // if the decryption has been successful..
    if (strippedMessage != null) {
        // I put the private key's public certificate as a mailattribute.
        // I create a list of certificate because I want to minic the
        // behavior of the SMIMEVerifySignature mailet. In that way
        // it is possible to reuse the same matchers to analyze
        // the result of the operation.
        ArrayList<X509Certificate> list = new ArrayList<X509Certificate>(1);
        list.add(keyHolder.getCertificate());
        mail.setAttribute(mailAttribute, list);

        // I start the message stripping.
        try {
            MimeMessage newMessage = new MimeMessage(message);
            newMessage.setText(text(strippedMessage), Charsets.UTF_8.name());
            if (!strippedMessage.isMimeType("multipart/*")) {
                newMessage.setDisposition(null);
            }
            newMessage.saveChanges();
            mail.setMessage(newMessage);
        } catch (IOException e) {
            log("Error during the strip of the encrypted message");
            throw new MessagingException("Error during the stripping of the encrypted message", e);
        }
    }
}

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

@Override
public Message getMessage(int index) throws MessagingException {
    File f;/*from   ww  w  .j a v  a  2  s  . co  m*/
    if (isFile) {
        f = folderPath;
    } else {
        f = new File(folderPath, String.format(FILENAME_FORMAT, Integer.valueOf(index)));
    }
    try {
        InputStream fis = new BufferedInputStream(new FileInputStream(f));
        try {
            Message m = new MailFileMessage(this, fis, index);
            return m;
        } finally {
            IOUtils.closeQuietly(fis);
        }
    } catch (FileNotFoundException e) {
        throw new MessagingException("Cannot open folder: " + e.getMessage(), e);
    }
}

From source file:org.apache.jsieve.mailet.SieveMailboxMailet.java

@Override
public void init(MailetConfig config) throws MessagingException {

    super.init(config);

    try {//  w ww  .j ava  2s  .  com
        final ConfigurationManager configurationManager = new ConfigurationManager();
        final int logLevel;
        if (verbose) {
            logLevel = CommonsLoggingAdapter.TRACE;
        } else if (quiet) {
            logLevel = CommonsLoggingAdapter.FATAL;
        } else {
            logLevel = CommonsLoggingAdapter.WARN;
        }
        log = new CommonsLoggingAdapter(this, logLevel);
        configurationManager.setLog(log);
        factory = configurationManager.build();
    } catch (SieveConfigurationException e) {
        throw new MessagingException("Failed to load standard Sieve configuration.", e);
    }
}

From source file:org.dspace.app.cris.batch.ScriptStatSubscribe.java

/**
 * Sends an email to the given e-person with statistics details of the
 * subscribed objects.// w  w w .  j a v  a2 s.  co  m
 * 
 * @param context
 *            DSpace context object
 * @param eperson
 *            eperson to send to
 * @param statSubscriptions
 *            List of DSpace Objects
 * @param test
 * @throws IOException
 */
public static void sendEmail(Context context, StatSubscribeService service, EPerson eperson,
        List<StatSubscription> statSubscriptions, int freq, boolean test)
        throws MessagingException, IOException {
    String sfreq = null;
    switch (freq) {
    case StatSubscription.FREQUENCY_DAILY:
        sfreq = "daily";
        break;

    case StatSubscription.FREQUENCY_WEEKLY:
        sfreq = "weekly";
        break;

    case StatSubscription.FREQUENCY_MONTHLY:
        sfreq = "monthly";
        break;

    default:
        throw new IllegalArgumentException("Unknow frequency: " + freq);
    }

    // Get a resource bundle according to the eperson language preferences
    Locale supportedLocale = I18nUtil.getEPersonLocale(eperson);

    String tmpfile = ConfigurationManager.getProperty(SolrLogger.CFG_STAT_MODULE, "subscribe-stat.tmpdir")
            + File.separator + "stat-" + sfreq + eperson.getID() + "_" + Thread.currentThread().getId()
            + ".xls";
    File file = new File(tmpfile);
    OutputStream os = null;
    try {
        os = new FileOutputStream(tmpfile);

        WritableWorkbook workbook = Workbook.createWorkbook(os);

        int r = 0;
        WritableSheet sheet = null;
        int sheetNumber = 0;

        int oldType = -1;
        for (StatSubscription statSub : statSubscriptions) {
            boolean changedType = false;
            if (oldType != statSub.getTypeDef()) {
                changedType = true;
                r = 0;
            }
            oldType = statSub.getTypeDef();
            SummaryStatBean statdetails = getStatBean(context, service, statSub);

            r++;
            if (statdetails == null)
                continue;

            SummaryStatBean.StatDataBean statDataBean = statdetails.getData().get(0);

            if (changedType) {
                sheet = workbook.createSheet(
                        I18nUtil.getMessage("it.cilea.hku.statistics.Subscribe.sheet." + statdetails.getType()),
                        sheetNumber);
                WritableFont labelFont = new WritableFont(WritableFont.ARIAL, 10, WritableFont.BOLD);
                WritableCellFormat cfobj = new WritableCellFormat(labelFont);
                sheet.addCell(
                        new Label(0, 0, I18nUtil.getMessage("it.cilea.hku.statistics.Subscribe.type"), cfobj));
                sheet.addCell(
                        new Label(1, 0, I18nUtil.getMessage("it.cilea.hku.statistics.Subscribe.name"), cfobj));
                sheet.addCell(
                        new Label(2, 0, I18nUtil.getMessage("it.cilea.hku.statistics.Subscribe.url"), cfobj));
                sheet.addCell(new Label(3, 0,
                        I18nUtil.getMessage("it.cilea.hku.statistics.Subscribe.totalView"), cfobj));
                sheet.addCell(new Label(4, 0,
                        I18nUtil.getMessage("it.cilea.hku.statistics.Subscribe." + sfreq + "View"), cfobj));

                int headerCell = 4;
                if (statDataBean.isShowSelectedObjectDownload()) {
                    sheet.addCell(new Label(++headerCell, 0,
                            I18nUtil.getMessage("it.cilea.hku.statistics.Subscribe.totalDownload"), cfobj));
                    sheet.addCell(new Label(++headerCell, 0,
                            I18nUtil.getMessage("it.cilea.hku.statistics.Subscribe." + sfreq + "Download"),
                            cfobj));
                }
                for (String topKey : statDataBean.getPeriodAndTotalTopView().keySet()) {
                    if (!statDataBean.getPeriodAndTotalTopView().get(topKey).isEmpty()) {
                        sheet.addCell(
                                new Label(++headerCell, 0,
                                        I18nUtil.getMessage(
                                                "it.cilea.hku.statistics.Subscribe.total" + topKey + "View"),
                                        cfobj));
                        sheet.addCell(new Label(++headerCell, 0,
                                I18nUtil.getMessage(
                                        "it.cilea.hku.statistics.Subscribe." + sfreq + topKey + "View"),
                                cfobj));
                    }
                }
                for (String topKey : statDataBean.getPeriodAndTotalTopDownload().keySet()) {
                    if (!statDataBean.getPeriodAndTotalTopDownload().get(topKey).isEmpty()) {
                        sheet.addCell(new Label(++headerCell, 0,
                                I18nUtil.getMessage(
                                        "it.cilea.hku.statistics.Subscribe.total" + topKey + "Download"),
                                cfobj));
                        sheet.addCell(new Label(++headerCell, 0,
                                I18nUtil.getMessage(
                                        "it.cilea.hku.statistics.Subscribe." + sfreq + topKey + "Download"),
                                cfobj));
                    }
                }
                for (int i = 0; i < headerCell; i++) {
                    final CellView view = sheet.getColumnView(i);
                    view.setAutosize(true);
                    sheet.setColumnView(i, view);
                }
                sheetNumber++;
            }
            sheet.addCell(new Label(0, r,
                    I18nUtil.getMessage("it.cilea.hku.statistics.Subscribe.type." + statdetails.getType())));
            sheet.addCell(new Label(1, r, statdetails.getObjectName()));
            sheet.addCell(new Label(2, r, statdetails.getObjectURL()));
            if (statDataBean.getTotalSelectedView() == -1) {
                sheet.addCell(new Label(3, r, I18nUtil.getMessage("it.cilea.hku.statistics.Subscribe.na")));
            } else {
                sheet.addCell(new Label(3, r, new Long(statDataBean.getTotalSelectedView()).toString()));
            }

            if (statDataBean.getPeriodSelectedView() == -1) {
                sheet.addCell(new Label(4, r, I18nUtil.getMessage("it.cilea.hku.statistics.Subscribe.na")));
            } else {
                sheet.addCell(new Label(4, r, new Long(statDataBean.getPeriodSelectedView()).toString()));
            }

            int countTopCell = 4;
            if (statDataBean.isShowSelectedObjectDownload()) {
                if (statDataBean.getTotalSelectedDownload() == -1) {
                    sheet.addCell(new Label(++countTopCell, r,
                            I18nUtil.getMessage("it.cilea.hku.statistics.Subscribe.na")));
                } else {
                    sheet.addCell(new Label(++countTopCell, r,
                            new Long(statDataBean.getTotalSelectedDownload()).toString()));
                }
                if (statDataBean.getPeriodSelectedDownload() == -1) {
                    sheet.addCell(new Label(++countTopCell, r,
                            I18nUtil.getMessage("it.cilea.hku.statistics.Subscribe.na")));
                } else {
                    sheet.addCell(new Label(++countTopCell, r,
                            new Long(statDataBean.getPeriodSelectedDownload()).toString()));
                }

            }
            for (String topKey : statDataBean.getPeriodAndTotalTopView().keySet()) {
                List<Long> tmpList = statDataBean.getPeriodAndTotalTopView().get(topKey);
                if (!tmpList.isEmpty()) {
                    if (tmpList.get(1) == null) {
                        sheet.addCell(new Label(++countTopCell, r,
                                I18nUtil.getMessage("it.cilea.hku.statistics.Subscribe.na")));
                    } else {
                        sheet.addCell(new Label(++countTopCell, r, new Long(tmpList.get(1)).toString()));
                    }
                }
                if (!tmpList.isEmpty()) {
                    if (tmpList.get(0) == null) {
                        sheet.addCell(new Label(++countTopCell, r,
                                I18nUtil.getMessage("it.cilea.hku.statistics.Subscribe.na")));
                    } else {
                        sheet.addCell(new Label(++countTopCell, r, new Long(tmpList.get(0)).toString()));
                    }
                }
            }
            for (String topKey : statDataBean.getPeriodAndTotalTopDownload().keySet()) {
                List<Long> tmpList = statDataBean.getPeriodAndTotalTopDownload().get(topKey);
                if (!tmpList.isEmpty()) {
                    if (tmpList.get(1) == null) {
                        sheet.addCell(new Label(++countTopCell, r,
                                I18nUtil.getMessage("it.cilea.hku.statistics.Subscribe.na")));
                    } else {
                        sheet.addCell(new Label(++countTopCell, r, new Long(tmpList.get(1)).toString()));
                    }
                }
                if (!tmpList.isEmpty()) {
                    if (tmpList.get(0) == null) {
                        sheet.addCell(new Label(++countTopCell, r,
                                I18nUtil.getMessage("it.cilea.hku.statistics.Subscribe.na")));
                    } else {
                        sheet.addCell(new Label(++countTopCell, r, new Long(tmpList.get(0)).toString()));
                    }
                }
            }

        }
        workbook.write();
        workbook.close();
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw new MessagingException("Failed to create the stat report attachment", e);
    } finally {
        if (os != null) {
            os.close();
        }
    }

    if (test) {
        System.out.println("After check remove the follow file: " + tmpfile);
    } else {
        Email email = Email.getEmail(I18nUtil.getEmailFilename(supportedLocale, "statsubscription-" + sfreq));
        email.addRecipient(eperson.getEmail());
        email.addArgument(ConfigurationManager.getProperty("dspace.url")
                + "/rp/tools/stats/subscription/unsubscribe?clear=all");
        email.addArgument(
                ConfigurationManager.getProperty("dspace.url") + "/rp/tools/stats/subscription/list.htm");
        email.addAttachment(file, "stat-" + sfreq + "-update.xls");
        email.send();
        file.delete();
    }
    log.info(LogManager.getHeader(context, "sent_statsubscription",
            "eperson_id=" + eperson.getID() + ", freq=" + sfreq));
}

From source file:org.eurekastreams.server.service.actions.strategies.EmailerFactory.java

/**
 * Retrieves the multipart object from the message.
 *
 * @param message/*w ww.  jav a2 s.  com*/
 *            Email message being built.
 * @return multipart object.
 * @throws MessagingException
 *             If there is a problem retrieving the content.
 */
protected Multipart getMultipart(final MimeMessage message) throws MessagingException {
    try {
        return (Multipart) message.getContent();
    } catch (IOException ex) {
        throw new MessagingException("Failed to retrieve multipart from message being built.", ex);
    }
}

From source file:org.masukomi.aspirin.core.Bouncer.java

/**
 * This generates a response to the Return-Path address, or the address of
 * the message's sender if the Return-Path is not available. Note that this
 * is different than a mail-client's reply, which would use the Reply-To or
 * From header.//  w w w  . j a  v a  2 s .co  m
 * 
 * @param mail
 *            DOCUMENT ME!
 * @param message
 *            DOCUMENT ME!
 * @param bouncer
 *            DOCUMENT ME!
 * 
 * @throws MessagingException
 *             DOCUMENT ME!
 */
static public void bounce(MailQue que, Mail mail, String message, MailAddress bouncer)
        throws MessagingException {
    if (bouncer != null) {
        if (log.isDebugEnabled()) {
            log.debug("bouncing message to postmaster");
        }
        MimeMessage orig = mail.getMessage();
        //Create the reply message
        MimeMessage reply = (MimeMessage) orig.reply(false);
        //If there is a Return-Path header,
        if (orig.getHeader(RFC2822Headers.RETURN_PATH) != null) {
            //Return the message to that address, not to the Reply-To
            // address
            reply.setRecipient(MimeMessage.RecipientType.TO,
                    new InternetAddress(orig.getHeader(RFC2822Headers.RETURN_PATH)[0]));
        }
        //Create the list of recipients in our MailAddress format
        Collection recipients = new HashSet();
        Address[] addresses = reply.getAllRecipients();
        for (int i = 0; i < addresses.length; i++) {
            recipients.add(new MailAddress((InternetAddress) addresses[i]));
        }
        //Change the sender...
        reply.setFrom(bouncer.toInternetAddress());
        try {
            //Create the message body
            MimeMultipart multipart = new MimeMultipart();
            //Add message as the first mime body part
            MimeBodyPart part = new MimeBodyPart();
            part.setContent(message, "text/plain");
            part.setHeader(RFC2822Headers.CONTENT_TYPE, "text/plain");
            multipart.addBodyPart(part);
            //Add the original message as the second mime body part
            part = new MimeBodyPart();
            part.setContent(orig.getContent(), orig.getContentType());
            part.setHeader(RFC2822Headers.CONTENT_TYPE, orig.getContentType());
            multipart.addBodyPart(part);
            reply.setHeader(RFC2822Headers.DATE, rfc822DateFormat.format(new Date()));
            reply.setContent(multipart);
            reply.setHeader(RFC2822Headers.CONTENT_TYPE, multipart.getContentType());
        } catch (IOException ioe) {
            throw new MessagingException("Unable to create multipart body", ioe);
        }
        //Send it off...
        //sendMail( bouncer, recipients, reply );
        que.queMail(reply);
    }
}