Example usage for org.apache.commons.mail.util MimeMessageParser hasPlainContent

List of usage examples for org.apache.commons.mail.util MimeMessageParser hasPlainContent

Introduction

In this page you can find the example usage for org.apache.commons.mail.util MimeMessageParser hasPlainContent.

Prototype

public boolean hasPlainContent() 

Source Link

Usage

From source file:com.opinionlab.woa.Awesome.java

public Awesome(Message message) {
    try {//from w w w .j  ava  2s  .co  m
        this.messageID = ((MimeMessage) message).getMessageID();
        this.id = ID_PTN.matcher(this.messageID).replaceAll("_");

        this.receivedDate = message.getReceivedDate();
        this.monthDay = DATE_FORMATTER
                .format(LocalDateTime.ofInstant(receivedDate.toInstant(), systemDefault()));
        this.to = new Person((InternetAddress) //todo Do this smarter
        message.getRecipients(Message.RecipientType.TO)[0]);
        this.from = new Person((InternetAddress) message.getFrom()[0]);
        this.subject = message.getSubject();

        final MimeMessageParser parser = new MimeMessageParser((MimeMessage) message).parse();
        if (!parser.hasPlainContent()) {
            LOGGER.error(format("Unable to parse message '%s'; has no plain content", this.messageID));
            this.comment = "Unknown content.";
        } else {
            this.comment = parseContent(parser.getPlainContent());
        }
    } catch (Throwable t) {
        throw new IllegalArgumentException(t);
    }
}

From source file:org.mangelp.fakeSmtpWeb.httpServer.mailBrowser.MailFile.java

/**
 * Parse the file on disk using a MimeMessageParser and set all the instance
 * properties we will be using./*from   w  ww  .ja  v a  2s.  co m*/
 *
 * @throws FileNotFoundException
 * @throws MessagingException
 * @throws ParseException
 * @throws IOException
 */
protected void parseEmail() throws FileNotFoundException, MessagingException, ParseException, IOException {

    InputStream inputStream = new BufferedInputStream(new FileInputStream(this.getFile()));

    try {
        final Session session = Session.getDefaultInstance(new Properties());

        MimeMessage message = new MimeMessage(session, inputStream);
        MimeMessageParser mimeParser = new MimeMessageParser(message);

        mimeParser.parse();

        this.setSubject(mimeParser.getSubject());
        this.setFrom(mimeParser.getFrom());
        this.setReplyTo(mimeParser.getReplyTo());

        ArrayList<String> toList = new ArrayList<String>();
        for (Address emailAddress : mimeParser.getTo()) {
            toList.add(emailAddress.toString());
        }

        this.setTo(toList.toArray(this.getTo()));

        ArrayList<String> ccList = new ArrayList<String>();
        for (Address emailAddress : mimeParser.getCc()) {
            ccList.add(emailAddress.toString());
        }

        this.setCc(ccList.toArray(this.getCc()));

        ArrayList<String> bccList = new ArrayList<String>();
        for (Address emailAddress : mimeParser.getBcc()) {
            bccList.add(emailAddress.toString());
        }

        this.setBcc(bccList.toArray(this.getBcc()));

        if (mimeParser.hasAttachments()) {
            attachments = new ArrayList<MailAttachment>(mimeParser.getAttachmentList().size());

            int index = 0;
            for (DataSource ds : mimeParser.getAttachmentList()) {
                attachments.add(new MailAttachment(++index, ds));
            }
        }

        if (mimeParser.hasHtmlContent()) {
            this.setHtmlContent(mimeParser.getHtmlContent());
        }

        if (mimeParser.hasPlainContent()) {
            this.setPlainContent(mimeParser.getPlainContent());
        }

    } catch (Exception e) {
        throw new ParseException("Failed to parse file " + this.getFile().toString() + ": " + e.getMessage());
    }

    this.setId(DigestUtils.sha1Hex(inputStream));

    inputStream.close();
}

From source file:won.bot.framework.component.needproducer.impl.MailFileNeedProducer.java

@Override
public synchronized Model readNeedFromFile(final File file) throws IOException {
    logger.debug("processing as mail file: {} ", file);
    FileInputStream fis = new FileInputStream(file);
    NeedModelBuilder needModelBuilder = new NeedModelBuilder();
    try {//  www. j a  va 2 s  .co m
        MimeMessage emailMessage = new MimeMessage(null, fis);
        MimeMessageParser parser = new MimeMessageParser(emailMessage);
        parser.parse();
        needModelBuilder.setTitle(parser.getSubject());
        String content = null;
        if (parser.hasPlainContent()) {
            content = parser.getPlainContent();
        } else if (parser.hasHtmlContent()) {
            Document doc = Jsoup.parse(parser.getHtmlContent());
            content = doc.text();
        }
        if (content != null) {
            needModelBuilder.setDescription(content);
        }
        logger.debug("mail subject          : {}", parser.getSubject());
        logger.debug("mail has plain content: {}", parser.hasPlainContent());
        logger.debug("mail has html content : {}", parser.hasHtmlContent());
        logger.debug("mail has attachments  : {}", parser.hasAttachments());
        logger.debug("mail plain content    : {}", StringUtils.abbreviate(parser.getPlainContent(), 200));
        logger.debug("mail html content     : {}", StringUtils.abbreviate(parser.getHtmlContent(), 200));
        needModelBuilder.setUri("no:uri");
        return needModelBuilder.build();
    } catch (Exception e) {
        logger.debug("could not parse email from file {} ", file, e);
    } finally {
        if (fis != null)
            fis.close();
    }
    return null;
}

From source file:won.preprocessing.MailProcessing.java

/**
 * Read mail files from the input folder, extract several fields (e.g. subject, content, from,
 * to) and save this data back into a text file of the output folder.
 *
 * @param inputFolder  input folder with the mails
 * @param outputFolder output folder with extracted content files
 * @throws IOException//w ww .  j  av a  2  s.  c  o m
 */
private static void preprocessMails(String inputFolder, String outputFolder) throws IOException {

    File inFolder = new File(inputFolder);
    File outFolder = new File(outputFolder);
    outFolder.mkdirs();

    if (!inFolder.isDirectory()) {
        throw new IOException("Input folder not a directory: " + inputFolder);
    }
    if (!outFolder.isDirectory()) {
        throw new IOException("Output folder not a directory: " + outputFolder);
    }

    logger.info("preprocessing mail files: ");
    logger.info("- input folder {}", inputFolder);
    logger.info("- output folder {}", outputFolder);

    for (File file : inFolder.listFiles()) {
        if (file.isDirectory()) {
            continue;
        }

        logger.debug("processing mail file: {} ", file);
        FileInputStream fis = null;
        Writer fw = null;

        try {
            fis = new FileInputStream(file);
            MimeMessage emailMessage = new MimeMessage(null, fis);
            MimeMessageParser parser = new MimeMessageParser(emailMessage);
            parser.parse();
            String content = null;
            if (parser.hasPlainContent()) {
                content = parser.getPlainContent();
                int endIndex = content.indexOf("-------------");
                if (endIndex != -1) {
                    content = content.substring(0, endIndex);
                }
            } else {
                logger.warn("no plain content in file: {}, use HTML content", file);
                content = parser.getHtmlContent();
            }

            File outfile = new File(outputFolder + "/" + file.getName());
            logger.debug("writing output file: {}", outfile.getAbsolutePath());
            logger.debug("- mail subject: {}", parser.getSubject());
            FileOutputStream outputStream = new FileOutputStream(outfile);

            // Enforce UTF-8 when writing files. Non UTF-8 files will be reported.
            fw = new OutputStreamWriter(outputStream, Charset.forName("UTF-8"));

            fw.append(FROM_PREFIX + parser.getFrom() + "\n");
            fw.append(TO_PREFIX + parser.getTo() + "\n");
            fw.append(DATE_PREFIX + emailMessage.getSentDate() + "\n");
            fw.append(SUBJECT_PREFIX + parser.getSubject() + "\n");
            fw.append(CONTENT_PREFIX + /*parser.getPlainContent()*/content + "\n");

        } catch (MessagingException me) {
            logger.error("Error opening mail file: " + file.getAbsolutePath(), me);
        } catch (IOException ioe) {
            logger.error("Error writing file: " + file.getAbsolutePath(), ioe);
            System.err.println("Error writing file: " + file.getAbsolutePath());
        } catch (Exception e) {
            logger.error("Error parsing mail file: " + file.getAbsolutePath(), e);
        } finally {
            if (fis != null)
                fis.close();
            if (fw != null)
                fw.close();
        }
    }
}