Example usage for javax.mail.internet MailDateFormat MailDateFormat

List of usage examples for javax.mail.internet MailDateFormat MailDateFormat

Introduction

In this page you can find the example usage for javax.mail.internet MailDateFormat MailDateFormat.

Prototype

public MailDateFormat() 

Source Link

Document

Create a new date format for the RFC2822 specification with lenient parsing.

Usage

From source file:com.icegreen.greenmail.store.SimpleMessageAttributes.java

SimpleMessageAttributes(MimeMessage msg, Date receivedDate) throws MessagingException {
    Date sentDate = getSentDate(msg, receivedDate);

    this.receivedDate = receivedDate;
    this.receivedDateString = new MailDateFormat().format(receivedDate);
    this.sentDateEnvelopeString = new MailDateFormat().format(sentDate);

    if (msg != null) {
        parseMimePart(msg);//  w  ww.  ja  va2 s.  co m
    }
}

From source file:it.unimi.di.big.mg4j.document.JavamailDocumentCollection.java

public Document document(final long index) throws IOException {
    try {//from  w  w  w  .ja v  a 2s . co  m
        return new AbstractDocument() {
            // Can you believe that? Javamail numbers messages from 1...
            final Message message = folder.getMessage((int) (index + 1));

            public CharSequence title() {
                final String subject;
                try {
                    subject = message.getSubject();
                } catch (MessagingException e) {
                    throw new RuntimeException(e.toString());
                }
                if (subject == null)
                    return (CharSequence) factory.resolve(MetadataKeys.TITLE, factory.defaultMetadata);
                else
                    return subject;
            }

            public CharSequence uri() {
                try {
                    return folder.getURLName() + "#" + message.getMessageNumber();
                } catch (MessagingException e) {
                    throw new RuntimeException(e);
                }
            }

            private Reader joinAddresses(final Address address[]) {
                if (address == null)
                    return NullReader.getInstance();
                final MutableString s = new MutableString();
                if (address != null) {
                    for (int i = 0; i < address.length; i++) {
                        if (i > 0)
                            s.append(", ");
                        s.append(address[i]);
                    }
                }
                return new FastBufferedReader(s);
            }

            public Object content(final int field) throws IOException {
                factory.ensureFieldIndex(field);
                try {
                    switch (field) {
                    case 0: // body
                        // TODO: analyze multipart messages
                        Object content = null;
                        try {
                            content = message.getContent();
                        } catch (Exception e) {
                            LOGGER.warn("Message " + message.getMessageNumber()
                                    + " cannot be decoded; content will be empty", e);
                        }

                        if (content != null && content instanceof String)
                            return new StringReader((String) content);

                        return NullReader.getInstance();
                    case 1: // subject
                        return message.getSubject() == null ? NullReader.getInstance()
                                : new StringReader(message.getSubject());
                    case 2: // from
                        return joinAddresses(message.getFrom());
                    case 3: // to 
                        return joinAddresses(message.getRecipients(Message.RecipientType.TO));
                    case 4: // date
                        final String[] date = message.getHeader("date");
                        if (date == null || date.length == 0)
                            return NO_DATE;
                        final MailDateFormat mailDateFormat = new MailDateFormat();
                        try {
                            return mailDateFormat.parse(date[0]);
                        } catch (ParseException e) {
                            LOGGER.warn("Error parsing date " + date[0]);
                            return NO_DATE;
                        }

                    case 5: // cc
                        return joinAddresses(message.getRecipients(Message.RecipientType.CC));
                    case 6: // bcc
                        return joinAddresses(message.getRecipients(Message.RecipientType.BCC));
                    case 7: // content-type
                        return new StringReader(message.getContentType());
                    }
                } catch (MessagingException e) {
                    // A simple error
                    if (e instanceof AddressException) {
                        LOGGER.warn("Error while parsing address", e);
                        return NullReader.getInstance();
                    }
                    throw new IOException(e.toString());
                }
                throw new IllegalStateException();
            }

            public WordReader wordReader(final int field) {
                factory.ensureFieldIndex(field);
                return factory.wordReader;
            }
        };
    } catch (MessagingException e) {
        throw new IOException(e.toString());
    }
}

From source file:com.stimulus.archiva.domain.Email.java

public Date getReceivedDate() {
    MailDateFormat mdf = new MailDateFormat();

    try {/*from  w  w w  .j  a  v  a  2  s .  c  om*/

        /*  Enumeration e = getAllHeaders();
          while (e.hasMoreElements()) {
             Header h = (Header)e.nextElement();
             System.out.println(h.getName()+":"+h.getValue());
          }*/
        String[] header = getHeader("Received");
        if (header == null || header.length < 1) {
            return null;
        }
        for (int i = 0; i < header.length; i++) {
            int received = header[i].lastIndexOf(';');
            if (received >= 0) {
                String dateStr = header[i].substring(received + 1).trim();
                Date date = mdf.parse(dateStr, new ParsePosition(0));
                return date;
            }
        }
    } catch (Exception re) {
        logger.debug("getReceivedDate(). unable to parse received date", re);
    }
    return null;
}

From source file:fr.gouv.culture.vitam.eml.EmlExtract.java

public static String extractInfoMessage(MimeMessage message, Element root, VitamArgument argument,
        ConfigLoader config) {//from w ww  .  jav  a  2 s .c o m
    File oldDir = argument.currentOutputDir;
    if (argument.currentOutputDir == null) {
        if (config.outputDir != null) {
            argument.currentOutputDir = new File(config.outputDir);
        }
    }
    Element keywords = XmlDom.factory.createElement(EMAIL_FIELDS.keywords.name);
    Element metadata = XmlDom.factory.createElement(EMAIL_FIELDS.metadata.name);
    String skey = "";
    String id = config.addRankId(root);
    Address[] from = null;
    Element sub2 = null;
    try {
        from = message.getFrom();
    } catch (MessagingException e1) {
        String[] partialResult;
        try {
            partialResult = message.getHeader("From");
            if (partialResult != null && partialResult.length > 0) {
                sub2 = XmlDom.factory.createElement(EMAIL_FIELDS.from.name);
                Element add = XmlDom.factory.createElement(EMAIL_FIELDS.fromUnit.name);
                add.setText(partialResult[0]);
                sub2.add(add);
            }
        } catch (MessagingException e) {
        }
    }
    Address sender = null;
    try {
        sender = message.getSender();
    } catch (MessagingException e1) {
        String[] partialResult;
        try {
            partialResult = message.getHeader("Sender");
            if (partialResult != null && partialResult.length > 0) {
                if (sub2 == null) {
                    sub2 = XmlDom.factory.createElement(EMAIL_FIELDS.from.name);
                    Element add = XmlDom.factory.createElement(EMAIL_FIELDS.fromUnit.name);
                    add.setText(partialResult[0]);
                    sub2.add(add);
                }
            }
        } catch (MessagingException e) {
        }
    }
    if (from != null && from.length > 0) {
        String value0 = null;
        Element sub = (sub2 != null ? sub2 : XmlDom.factory.createElement(EMAIL_FIELDS.from.name));
        if (sender != null) {
            value0 = addAddress(sub, EMAIL_FIELDS.fromUnit.name, sender, null);
        }
        for (Address address : from) {
            addAddress(sub, EMAIL_FIELDS.fromUnit.name, address, value0);
        }
        metadata.add(sub);
    } else if (sender != null) {
        Element sub = (sub2 != null ? sub2 : XmlDom.factory.createElement(EMAIL_FIELDS.from.name));
        addAddress(sub, EMAIL_FIELDS.fromUnit.name, sender, null);
        metadata.add(sub);
    } else {
        if (sub2 != null) {
            metadata.add(sub2);
        }
    }
    Address[] replyTo = null;
    try {
        replyTo = message.getReplyTo();
        if (replyTo != null && replyTo.length > 0) {
            Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.replyTo.name);
            for (Address address : replyTo) {
                addAddress(sub, EMAIL_FIELDS.fromUnit.name, address, null);
            }
            metadata.add(sub);
        }
    } catch (MessagingException e1) {
        String[] partialResult;
        try {
            partialResult = message.getHeader("ReplyTo");
            if (partialResult != null && partialResult.length > 0) {
                sub2 = XmlDom.factory.createElement(EMAIL_FIELDS.replyTo.name);
                addAddress(sub2, EMAIL_FIELDS.fromUnit.name, partialResult, null);
                /*Element add = XmlDom.factory.createElement(EMAIL_FIELDS.fromUnit.name);
                add.setText(partialResult[0]);
                sub2.add(add);*/
                metadata.add(sub2);
            }
        } catch (MessagingException e) {
        }
    }
    Address[] toRecipients = null;
    try {
        toRecipients = message.getRecipients(Message.RecipientType.TO);
        if (toRecipients != null && toRecipients.length > 0) {
            Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.toRecipients.name);
            for (Address address : toRecipients) {
                addAddress(sub, EMAIL_FIELDS.toUnit.name, address, null);
            }
            metadata.add(sub);
        }
    } catch (MessagingException e1) {
        String[] partialResult;
        try {
            partialResult = message.getHeader("To");
            if (partialResult != null && partialResult.length > 0) {
                sub2 = XmlDom.factory.createElement(EMAIL_FIELDS.toRecipients.name);
                addAddress(sub2, EMAIL_FIELDS.toUnit.name, partialResult, null);
                /*for (String string : partialResult) {
                   Element add = XmlDom.factory.createElement(EMAIL_FIELDS.toUnit.name);
                   add.setText(string);
                   sub2.add(add);
                }*/
                metadata.add(sub2);
            }
        } catch (MessagingException e) {
        }
    }
    Address[] ccRecipients;
    try {
        ccRecipients = message.getRecipients(Message.RecipientType.CC);
        if (ccRecipients != null && ccRecipients.length > 0) {
            Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.ccRecipients.name);
            for (Address address : ccRecipients) {
                addAddress(sub, EMAIL_FIELDS.ccUnit.name, address, null);
            }
            metadata.add(sub);
        }
    } catch (MessagingException e1) {
        String[] partialResult;
        try {
            partialResult = message.getHeader("Cc");
            if (partialResult != null && partialResult.length > 0) {
                sub2 = XmlDom.factory.createElement(EMAIL_FIELDS.ccRecipients.name);
                addAddress(sub2, EMAIL_FIELDS.ccUnit.name, partialResult, null);
                /*for (String string : partialResult) {
                   Element add = XmlDom.factory.createElement(EMAIL_FIELDS.ccUnit.name);
                   add.setText(string);
                   sub2.add(add);
                }*/
                metadata.add(sub2);
            }
        } catch (MessagingException e) {
        }
    }
    Address[] bccRecipients;
    try {
        bccRecipients = message.getRecipients(Message.RecipientType.BCC);
        if (bccRecipients != null && bccRecipients.length > 0) {
            Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.bccRecipients.name);
            for (Address address : bccRecipients) {
                addAddress(sub, EMAIL_FIELDS.bccUnit.name, address, null);
            }
            metadata.add(sub);
        }
    } catch (MessagingException e1) {
        String[] partialResult;
        try {
            partialResult = message.getHeader("Cc");
            if (partialResult != null && partialResult.length > 0) {
                sub2 = XmlDom.factory.createElement(EMAIL_FIELDS.bccRecipients.name);
                addAddress(sub2, EMAIL_FIELDS.bccUnit.name, partialResult, null);
                /*for (String string : partialResult) {
                   Element add = XmlDom.factory.createElement(EMAIL_FIELDS.bccUnit.name);
                   add.setText(string);
                   sub2.add(add);
                }*/
                metadata.add(sub2);
            }
        } catch (MessagingException e) {
        }
    }
    try {
        String subject = message.getSubject();
        if (subject != null) {
            Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.subject.name);
            sub.setText(StringUtils.unescapeHTML(subject, true, false));
            metadata.add(sub);
        }
        Date sentDate = message.getSentDate();
        if (sentDate != null) {
            Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.sentDate.name);
            sub.setText(sentDate.toString());
            metadata.add(sub);
        }
        Date receivedDate = message.getReceivedDate();
        if (receivedDate != null) {
            Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.receivedDate.name);
            sub.setText(receivedDate.toString());
            metadata.add(sub);
        }
        String[] headers = message.getHeader("Received");
        if (headers != null) {
            Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.receptionTrace.name);
            MailDateFormat mailDateFormat = null;
            long maxTime = 0;
            if (receivedDate == null) {
                mailDateFormat = new MailDateFormat();
            }
            for (String string : headers) {
                Element sub3 = XmlDom.factory.createElement(EMAIL_FIELDS.trace.name);
                sub3.setText(StringUtils.unescapeHTML(string, true, false));
                sub.add(sub3);
                if (receivedDate == null) {
                    int pos = string.lastIndexOf(';');
                    if (pos > 0) {
                        String recvdate = string.substring(pos + 2).replaceAll("\t\n\r\f", "").trim();
                        try {
                            Date date = mailDateFormat.parse(recvdate);
                            if (date.getTime() > maxTime) {
                                maxTime = date.getTime();
                            }
                        } catch (ParseException e) {
                        }
                    }
                }
            }
            if (receivedDate == null) {
                Element subdate = XmlDom.factory.createElement(EMAIL_FIELDS.receivedDate.name);
                Date date = new Date(maxTime);
                subdate.setText(date.toString());
                metadata.add(subdate);
            }
            metadata.add(sub);
        }
        int internalSize = message.getSize();
        if (internalSize > 0) {
            Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.emailSize.name);
            sub.setText(Integer.toString(internalSize));
            metadata.add(sub);
        }
        String encoding = message.getEncoding();
        if (encoding != null) {
            Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.encoding.name);
            sub.setText(StringUtils.unescapeHTML(encoding, true, false));
            metadata.add(sub);
        }
        String description = message.getDescription();
        if (description != null) {
            Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.description.name);
            sub.setText(StringUtils.unescapeHTML(description, true, false));
            metadata.add(sub);
        }
        String contentType = message.getContentType();
        if (contentType != null) {
            Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.contentType.name);
            sub.setText(StringUtils.unescapeHTML(contentType, true, false));
            metadata.add(sub);
        }
        headers = message.getHeader("Content-Transfer-Encoding");
        if (headers != null) {
            Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.contentTransferEncoding.name);
            StringBuilder builder = new StringBuilder();
            for (String string : headers) {
                builder.append(StringUtils.unescapeHTML(string, true, false));
                builder.append(' ');
            }
            sub.setText(builder.toString());
            metadata.add(sub);
        }
        String[] contentLanguage = message.getContentLanguage();
        if (contentLanguage != null) {
            Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.contentLanguage.name);
            StringBuilder builder = new StringBuilder();
            for (String string : contentLanguage) {
                builder.append(StringUtils.unescapeHTML(string, true, false));
                builder.append(' ');
            }
            sub.setText(builder.toString());
            metadata.add(sub);
        }
        String contentId = message.getContentID();
        if (contentId != null) {
            Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.contentId.name);
            sub.setText(StringUtils.removeChevron(StringUtils.unescapeHTML(contentId, true, false)));
            metadata.add(sub);
        }
        String disposition = message.getDisposition();
        if (disposition != null) {
            Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.disposition.name);
            sub.setText(StringUtils.removeChevron(StringUtils.unescapeHTML(disposition, true, false)));
            metadata.add(sub);
        }
        headers = message.getHeader("Keywords");
        if (headers != null) {
            Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.msgKeywords.name);
            StringBuilder builder = new StringBuilder();
            for (String string : headers) {
                builder.append(StringUtils.unescapeHTML(string, true, false));
                builder.append(' ');
            }
            sub.setText(builder.toString());
            metadata.add(sub);
        }
        String messageId = message.getMessageID();
        if (messageId != null) {
            messageId = StringUtils.removeChevron(StringUtils.unescapeHTML(messageId, true, false)).trim();
            if (messageId.length() > 1) {
                Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.messageId.name);
                sub.setText(messageId);
                metadata.add(sub);
            }
        }
        headers = message.getHeader("In-Reply-To");
        String inreplyto = null;
        if (headers != null) {
            StringBuilder builder = new StringBuilder();
            for (String string : headers) {
                builder.append(StringUtils.removeChevron(StringUtils.unescapeHTML(string, true, false)));
                builder.append(' ');
            }
            inreplyto = builder.toString().trim();
            if (inreplyto.length() > 0) {
                Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.inReplyTo.name);
                sub.setText(inreplyto);
                if (messageId != null && messageId.length() > 1) {
                    String old = filEmls.get(inreplyto);
                    if (old == null) {
                        old = messageId;
                    } else {
                        old += "," + messageId;
                    }
                    filEmls.put(inreplyto, old);
                }
                metadata.add(sub);
            }
        }
        headers = message.getHeader("References");
        if (headers != null) {
            Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.references.name);
            StringBuilder builder = new StringBuilder();
            for (String string : headers) {
                builder.append(StringUtils.removeChevron(StringUtils.unescapeHTML(string, true, false)));
                builder.append(' ');
            }
            String[] refs = builder.toString().trim().split(" ");
            for (String string : refs) {
                if (string.length() > 0) {
                    Element ref = XmlDom.factory.createElement(EMAIL_FIELDS.reference.name);
                    ref.setText(string);
                    sub.add(ref);
                }
            }
            metadata.add(sub);
        }
        Element prop = XmlDom.factory.createElement(EMAIL_FIELDS.properties.name);
        headers = message.getHeader("X-Priority");
        if (headers == null) {
            headers = message.getHeader("Priority");
            if (headers != null && headers.length > 0) {
                prop.addAttribute(EMAIL_FIELDS.priority.name, headers[0]);
            }
        } else if (headers != null && headers.length > 0) {
            String imp = headers[0];
            try {
                int Priority = Integer.parseInt(imp);
                switch (Priority) {
                case 5:
                    imp = "LOWEST";
                    break;
                case 4:
                    imp = "LOW";
                    break;
                case 3:
                    imp = "NORMAL";
                    break;
                case 2:
                    imp = "HIGH";
                    break;
                case 1:
                    imp = "HIGHEST";
                    break;
                default:
                    imp = "LEV" + Priority;
                }
            } catch (NumberFormatException e) {
                // ignore since imp will be used as returned
            }
            prop.addAttribute(EMAIL_FIELDS.priority.name, imp);
        }
        headers = message.getHeader("Sensitivity");
        if (headers != null && headers.length > 0) {
            prop.addAttribute(EMAIL_FIELDS.sensitivity.name, headers[0]);
        }
        headers = message.getHeader("X-RDF");
        if (headers != null && headers.length > 0) {
            System.err.println("Found X-RDF");
            StringBuilder builder = new StringBuilder();
            for (String string : headers) {
                builder.append(string);
                builder.append("\n");
            }
            try {
                byte[] decoded = org.apache.commons.codec.binary.Base64.decodeBase64(builder.toString());
                String rdf = new String(decoded);
                Document tempDocument = DocumentHelper.parseText(rdf);
                Element xrdf = prop.addElement("x-rdf");
                xrdf.add(tempDocument.getRootElement());
            } catch (Exception e) {
                System.err.println("Cannot decode X-RDF: " + e.getMessage());
            }
        }
        try {
            File old = argument.currentOutputDir;
            if (config.extractFile) {
                File newOutDir = new File(argument.currentOutputDir, id);
                newOutDir.mkdirs();
                argument.currentOutputDir = newOutDir;
            }
            if (argument.extractKeyword) {
                skey = handleMessage(message, metadata, prop, id, argument, config);
                // should have hasAttachment
                if (prop.hasContent()) {
                    metadata.add(prop);
                }
                if (metadata.hasContent()) {
                    root.add(metadata);
                }
                ExtractInfo.exportMetadata(keywords, skey, "", config, null);
                if (keywords.hasContent()) {
                    root.add(keywords);
                }
            } else {
                handleMessage(message, metadata, prop, id, argument, config);
                // should have hasAttachment
                if (prop.hasContent()) {
                    metadata.add(prop);
                }
                if (metadata.hasContent()) {
                    root.add(metadata);
                }
            }
            argument.currentOutputDir = old;
        } catch (IOException e) {
            System.err.println(StaticValues.LBL.error_error.get() + e.toString());
        }
        try {
            message.getInputStream().close();
        } catch (IOException e) {
            System.err.println(StaticValues.LBL.error_error.get() + e.toString());
        }
        root.addAttribute(EMAIL_FIELDS.status.name, "ok");
    } catch (MessagingException e) {
        System.err.println(StaticValues.LBL.error_error.get() + e.toString());
        e.printStackTrace();
        String status = "Error during identification";
        root.addAttribute(EMAIL_FIELDS.status.name, status);
    } catch (Exception e) {
        System.err.println(StaticValues.LBL.error_error.get() + e.toString());
        e.printStackTrace();
        String status = "Error during identification";
        root.addAttribute(EMAIL_FIELDS.status.name, status);
    }
    argument.currentOutputDir = oldDir;
    return skey;
}

From source file:org.georchestra.console.ws.emails.EmailController.java

/**
 * Send EmailEntry to smtp server//from ww  w .j  a va  2s  .  c  o  m
 *
 * @param email email to send
 * @throws NameNotFoundException if recipient cannot be found in LDAP server
 * @throws DataServiceException if LDAP server is not available
 * @throws MessagingException if some field of email cannot be encoded (malformed email address)
 */
private void send(EmailEntry email) throws NameNotFoundException, DataServiceException, MessagingException {

    final Session session = Session.getInstance(System.getProperties(), null);
    session.getProperties().setProperty("mail.smtp.host", this.emailFactory.getSmtpHost());
    session.getProperties().setProperty("mail.smtp.port",
            (new Integer(this.emailFactory.getSmtpPort())).toString());
    final MimeMessage message = new MimeMessage(session);

    Account recipient = this.accountDao.findByUID(email.getRecipient());
    InternetAddress[] senders = {
            new InternetAddress(this.accountDao.findByUID(email.getSender()).getEmail()) };

    message.addFrom(senders);
    message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient.getEmail()));
    message.setSubject(email.getSubject());
    message.setHeader("Date", (new MailDateFormat()).format(email.getDate()));

    // Mail content
    Multipart multiPart = new MimeMultipart("alternative");

    // attachments
    for (Attachment att : email.getAttachments()) {
        MimeBodyPart mbp = new MimeBodyPart();
        mbp.setDataHandler(new DataHandler(new ByteArrayDataSource(att.getContent(), att.getMimeType())));
        mbp.setFileName(att.getName());
        multiPart.addBodyPart(mbp);
    }

    // html part
    MimeBodyPart htmlPart = new MimeBodyPart();
    htmlPart.setContent(email.getBody(), "text/html; charset=utf-8");
    multiPart.addBodyPart(htmlPart);

    message.setContent(multiPart);

    // Send message
    Transport.send(message);
}

From source file:org.georchestra.ldapadmin.ws.emails.EmailController.java

/**
 * Send EmailEntry to smtp server/* w  ww  . j  a va  2 s .co m*/
 *
 * @param email email to send
 * @throws NameNotFoundException if recipient cannot be found in LDAP server
 * @throws DataServiceException if LDAP server is not available
 * @throws MessagingException if some field of email cannot be encoded (malformed email address)
 */
private void send(EmailEntry email) throws NameNotFoundException, DataServiceException, MessagingException {

    final Properties props = System.getProperties();
    props.put("mail.smtp.host", this.emailFactory.getSmtpHost());
    props.put("mail.protocol.port", this.emailFactory.getSmtpPort());

    final Session session = Session.getInstance(props, null);
    final MimeMessage message = new MimeMessage(session);

    Account recipient = this.accountDao.findByUID(email.getRecipient());
    InternetAddress[] senders = {
            new InternetAddress(this.accountDao.findByUID(email.getSender()).getEmail()) };

    message.addFrom(senders);
    message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient.getEmail()));
    message.setSubject(email.getSubject());
    message.setHeader("Date", (new MailDateFormat()).format(email.getDate()));

    // Mail content
    Multipart multiPart = new MimeMultipart("alternative");

    // attachments
    for (Attachment att : email.getAttachments()) {
        MimeBodyPart mbp = new MimeBodyPart();
        mbp.setDataHandler(new DataHandler(new ByteArrayDataSource(att.getContent(), att.getMimeType())));
        mbp.setFileName(att.getName());
        multiPart.addBodyPart(mbp);
    }

    // html part
    MimeBodyPart htmlPart = new MimeBodyPart();
    htmlPart.setContent(email.getBody(), "text/html; charset=utf-8");
    multiPart.addBodyPart(htmlPart);

    message.setContent(multiPart);

    // Send message
    Transport.send(message);
}

From source file:org.methodize.nntprss.admin.AdminServlet.java

private void cmdExportOpmlChannelConfig(HttpServletResponse response) throws ServletException, IOException {

    //      response.setContentType("text/xml");
    response.setContentType("application/octet-stream; charset=UTF-8");
    response.setHeader("Content-Disposition", "attachment; filename=\"nntprss-channels-opml.xml\"");
    PrintWriter writer = new PrintWriter(response.getWriter());
    writer.println("<?xml version='1.0' encoding='UTF-8'?>");
    writer.println();/*from w ww.j  a  v a2  s .co  m*/
    writer.println("<!-- Generated on " + new Date().toString() + " -->");
    writer.println("<!-- nntp//rss v" + XMLHelper.escapeString(AppConstants.VERSION)
            + " - http://www.methodize.org/nntprss/ -->");

    writer.println("<opml version='1.1'>");
    writer.println(" <head>");
    writer.println("  <title>My nntp//rss Subscriptions</title>");

    MailDateFormat mailDateFormat = new MailDateFormat();
    String currentDateTime = mailDateFormat.format(new Date());
    writer.println("  <dateCreated>" + currentDateTime + "</dateCreated>");
    writer.println("  <dateModified>" + currentDateTime + "</dateModified>");
    writer.println(" </head>");
    writer.println(" <body>");

    ChannelManager channelManager = (ChannelManager) getServletContext()
            .getAttribute(AdminServer.SERVLET_CTX_RSS_MANAGER);

    Iterator channelIter = channelManager.channels();
    while (channelIter.hasNext()) {
        Channel channel = (Channel) channelIter.next();
        writer.print("  <outline text='");
        writer.print(channel.getTitle() != null ? XMLHelper.escapeString(channel.getTitle()) : "");
        writer.print("' description='");
        writer.print(channel.getDescription() != null ? XMLHelper.escapeString(channel.getDescription()) : "");
        writer.print("' htmlUrl='");
        writer.print(channel.getLink() != null ? XMLHelper.escapeString(channel.getLink()) : "");
        writer.print("' title='");
        writer.print(channel.getTitle() != null ? XMLHelper.escapeString(channel.getTitle()) : "");
        writer.print("' ");
        if (channel.getRssVersion() != null) {
            if (channel.getRssVersion().toUpperCase().startsWith("RSS")
                    || channel.getRssVersion().startsWith("RDF")) {
                writer.print("type='rss' version='RSS' ");
            } else if (channel.getRssVersion().toUpperCase().startsWith("ATOM")) {
                writer.print("type='atom' version='ATOM' ");
            }
        }
        writer.print("xmlUrl='");
        writer.print(XMLHelper.escapeString(channel.getUrl()));
        writer.println("'/>");
    }

    writer.println(" </body>");
    writer.println("</opml>");
}

From source file:org.xwiki.contrib.mail.internal.JavamailMessageParser.java

/**
 * {@inheritDoc}/*from  w ww  .  ja  v  a  2  s . c  o  m*/
 * 
 * @throws MessagingException
 * @throws IOException
 * @see org.xwiki.contrib.mail.internal.IMessageParser#parseHeaders(java.lang.Object)
 */
@Override
public MailItem parseHeaders(Part mail) throws MessagingException, IOException {
    MailItem m = new MailItem();

    String[] headers;

    String value = null;

    value = extractSingleHeader(mail, "Message-ID");
    value = Utils.cropId(value);
    m.setMessageId(value);

    value = extractSingleHeader(mail, "In-Reply-To");
    value = Utils.cropId(value);
    m.setReplyToId(value);

    value = extractSingleHeader(mail, "References");
    m.setRefs(value);

    value = extractSingleHeader(mail, "Subject");
    if (StringUtils.isBlank(value)) {
        value = DEFAULT_SUBJECT;
    }
    value = value.replaceAll("[\n\r]", "").replaceAll(">", "&gt;").replaceAll("<", "&lt;");
    m.setSubject(value);

    // If topic is not provided, we use message subject without the beginning junk
    value = extractSingleHeader(mail, "Thread-Topic");
    if (StringUtils.isBlank(value)) {
        value = m.getSubject().replaceAll("(?mi)([\\[\\(] *)?(RE|FWD?) *([-:;)\\]][ :;\\])-]*|$)|\\]+ *$", "");
    } else {
        value = Utils.removeCRLF(value);
    }
    m.setTopic(value);

    // Topic Id : if none is provided, we use the message-id as topic id
    value = extractSingleHeader(mail, "Thread-Index");
    if (!StringUtils.isBlank(value)) {
        value = Utils.cropId(value);
    }
    m.setTopicId(value);

    value = extractSingleHeader(mail, "From");
    value = value.replaceAll("\"", "").replaceAll("[\n\r]", "");
    m.setFrom(value);

    value = extractSingleHeader(mail, "Sender");
    value = value.replaceAll("\"", "").replaceAll("[\n\r]", "");
    m.setSender(value);

    value = extractSingleHeader(mail, "To");
    value = value.replaceAll("\"", "").replaceAll("[\n\r]", "");
    m.setTo(value);

    value = extractSingleHeader(mail, "CC");
    value = value.replaceAll("\"", "").replaceAll("[\n\r]", "");
    m.setCc(value);

    // process the locale, if any provided
    String locLang = "en";
    String locCountry = "US";
    String language;
    headers = mail.getHeader("Content-Language");
    if (headers != null) {
        language = headers[0];
        if (language != null && !language.isEmpty()) {
            int index = language.indexOf('.');
            if (index != -1) {
                locLang = language.substring(0, index - 1);
                locCountry = language.substring(index);
            }
        }
    }
    Locale locale = new Locale(locLang, locCountry);
    m.setLocale(locale);

    String date = "";
    Date decodedDate = null;
    headers = mail.getHeader("Date");
    if (headers != null) {
        date = headers[0];
    }
    // Decode the date
    try {
        logger.debug("Parsing date [" + date + "] with Javamail MailDateFormat");
        decodedDate = new MailDateFormat().parse(date);
    } catch (ParseException e) {
        logger.debug("Could not parse date header " + ExceptionUtils.getRootCauseMessage(e));
        decodedDate = null;
    }
    if (decodedDate == null) {
        try {
            logger.debug("Parsing date [" + date + "] with GMail parser");
            decodedDate = new GMailMailDateFormat().parse(date);
        } catch (ParseException e) {
            logger.info(
                    "Could not parse date header with GMail parser " + ExceptionUtils.getRootCauseMessage(e));
            decodedDate = new Date();
            logger.info("Using 'now' as date as date could not be parsed");
        }
    }
    m.setDate(decodedDate);

    boolean firstInTopic = ("".equals(m.getReplyToId()));
    m.setFirstInTopic(firstInTopic);

    m.setOriginalMessage((Message) mail);
    m.setBodypart(mail.getContent());
    m.setContentType(mail.getContentType().toLowerCase());

    String sensitivity = "normal";
    headers = mail.getHeader("Sensitivity");
    if (headers != null && !headers[0].isEmpty()) {
        sensitivity = "normal";
    }
    m.setSensitivity(sensitivity.toLowerCase());

    String importance = "normal";
    headers = mail.getHeader("Importance");
    if (importance == null || importance == "") {
        importance = "normal";
    }
    m.setImportance(importance.toLowerCase());

    // type
    m.setBuiltinType("mail");

    return m;
}