Java Code Examples for javax.mail.internet.MimeUtility#unfold()

The following examples show how to use javax.mail.internet.MimeUtility#unfold() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MessageHelper.java    From FairEmail with GNU General Public License v3.0 6 votes vote down vote up
String getReceivedFromHost() throws MessagingException {
    ensureMessage(false);

    String[] received = imessage.getHeader("Received");
    if (received == null || received.length == 0)
        return null;

    String origin = MimeUtility.unfold(received[received.length - 1]);

    String[] h = origin.split("\\s+");
    if (h.length > 1 && h[0].equalsIgnoreCase("from")) {
        String host = h[1];
        if (host.startsWith("["))
            host = host.substring(1);
        if (host.endsWith("]"))
            host = host.substring(0, host.length() - 1);
        if (!TextUtils.isEmpty(host))
            return host;
    }

    return null;
}
 
Example 2
Source File: MessageHelper.java    From FairEmail with GNU General Public License v3.0 6 votes vote down vote up
String getSubject() throws MessagingException {
    ensureMessage(false);

    String subject = imessage.getHeader("Subject", null);
    if (subject == null)
        return null;

    subject = fixEncoding("subject", subject);
    subject = subject.replaceAll("\\?=[\\r\\n\\t ]+=\\?", "\\?==\\?");
    subject = MimeUtility.unfold(subject);
    subject = decodeMime(subject);

    return subject
            .trim()
            .replace("\n", "")
            .replace("\r", "");
}
 
Example 3
Source File: EnvelopeBuilder.java    From james-project with Apache License 2.0 6 votes vote down vote up
private String headerValue(Headers message, String headerName) throws MailboxException {
    final Header header = MessageResultUtils.getMatching(headerName, message.headers());
    final String result;
    if (header == null) {
        result = null;
    } else {
        final String value = header.getValue();
        if (value == null || "".equals(value)) {
            result = null;
        } else {

            // ENVELOPE header values must be unfolded
            // See IMAP-269
            //
            //
            // IMAP-Servers are advised to also replace tabs with single spaces while doing the unfolding. This is what javamails
            // unfold does. mime4j's unfold does strictly follow the rfc and so preserve them
            //
            // See IMAP-327 and https://mailman2.u.washington.edu/mailman/htdig/imap-protocol/2010-July/001271.html
            result = MimeUtility.unfold(value);

        }
    }
    return result;
}
 
Example 4
Source File: MessageHelper.java    From FairEmail with GNU General Public License v3.0 5 votes vote down vote up
String getMessageID() throws MessagingException {
    ensureMessage(false);

    // Outlook outbox -> sent
    String header = imessage.getHeader(HEADER_CORRELATION_ID, null);
    if (header == null)
        header = imessage.getHeader("Message-ID", null);
    return (header == null ? null : MimeUtility.unfold(header));
}
 
Example 5
Source File: MessageHelper.java    From FairEmail with GNU General Public License v3.0 5 votes vote down vote up
String getDeliveredTo() throws MessagingException {
    ensureMessage(false);

    String header = imessage.getHeader("Delivered-To", null);
    if (header == null)
        header = imessage.getHeader("X-Delivered-To", null);
    if (header == null)
        header = imessage.getHeader("Envelope-To", null);
    if (header == null)
        header = imessage.getHeader("X-Envelope-To", null);
    if (header == null)
        header = imessage.getHeader("X-Original-To", null);

    return (header == null ? null : MimeUtility.unfold(header));
}
 
Example 6
Source File: MessageHelper.java    From FairEmail with GNU General Public License v3.0 5 votes vote down vote up
String[] getAuthentication() throws MessagingException {
    ensureMessage(false);

    String[] headers = imessage.getHeader("Authentication-Results");
    if (headers == null)
        return null;

    for (int i = 0; i < headers.length; i++)
        headers[i] = MimeUtility.unfold(headers[i]);

    return headers;
}
 
Example 7
Source File: MessageHelper.java    From FairEmail with GNU General Public License v3.0 5 votes vote down vote up
String getAutocrypt() throws MessagingException {
    ensureMessage(false);

    String autocrypt = imessage.getHeader("Autocrypt", null);
    if (autocrypt == null)
        return null;

    return MimeUtility.unfold(autocrypt);
}
 
Example 8
Source File: ImapConnection.java    From davmail with GNU General Public License v2.0 5 votes vote down vote up
protected void appendMailEnvelopeHeader(StringBuilder buffer, String[] value) {
    buffer.append(' ');
    if (value != null && value.length > 0) {
        try {
            String unfoldedValue = MimeUtility.unfold(value[0]);
            InternetAddress[] addresses = InternetAddress.parseHeader(unfoldedValue, false);
            if (addresses.length > 0) {
                buffer.append('(');
                for (InternetAddress address : addresses) {
                    buffer.append('(');
                    String personal = address.getPersonal();
                    if (personal != null) {
                        appendEnvelopeHeaderValue(buffer, personal);
                    } else {
                        buffer.append("NIL");
                    }
                    buffer.append(" NIL ");
                    String mail = address.getAddress();
                    int atIndex = mail.indexOf('@');
                    if (atIndex >= 0) {
                        buffer.append('"').append(mail, 0, atIndex).append('"');
                        buffer.append(' ');
                        buffer.append('"').append(mail.substring(atIndex + 1)).append('"');
                    } else {
                        buffer.append("NIL NIL");
                    }
                    buffer.append(')');
                }
                buffer.append(')');
            } else {
                buffer.append("NIL");
            }
        } catch (AddressException | UnsupportedEncodingException e) {
            DavGatewayTray.warn(e);
            buffer.append("NIL");
        }
    } else {
        buffer.append("NIL");
    }
}
 
Example 9
Source File: UseHeaderRecipients.java    From james-project with Apache License 2.0 5 votes vote down vote up
private String sanitizeHeaderString(String header) throws MessagingException {
    try {
        return MimeUtility.unfold(MimeUtility.decodeText(header));
    } catch (UnsupportedEncodingException e) {
        throw new MessagingException("Can not decode header", e);
    }
}
 
Example 10
Source File: MessageHelper.java    From FairEmail with GNU General Public License v3.0 4 votes vote down vote up
String[] getReferences() throws MessagingException {
    ensureMessage(false);

    List<String> result = new ArrayList<>();
    String refs = imessage.getHeader("References", null);
    if (refs != null)
        result.addAll(Arrays.asList(getReferences(refs)));

    try {
        // Merge references of original message for threading
        if (imessage.isMimeType("multipart/report")) {
            ContentType ct = new ContentType(imessage.getContentType());
            String reportType = ct.getParameter("report-type");
            if ("delivery-status".equalsIgnoreCase(reportType) ||
                    "disposition-notification".equalsIgnoreCase(reportType)) {
                String arefs = null;
                String amsgid = null;

                MessageParts parts = new MessageParts();
                getMessageParts(imessage, parts, null);
                for (AttachmentPart apart : parts.attachments)
                    if ("text/rfc822-headers".equalsIgnoreCase(apart.attachment.type)) {
                        InternetHeaders iheaders = new InternetHeaders(apart.part.getInputStream());
                        arefs = iheaders.getHeader("References", null);
                        amsgid = iheaders.getHeader("Message-Id", null);
                        break;
                    } else if ("message/rfc822".equalsIgnoreCase(apart.attachment.type)) {
                        Properties props = MessageHelper.getSessionProperties();
                        Session isession = Session.getInstance(props, null);
                        MimeMessage amessage = new MimeMessage(isession, apart.part.getInputStream());
                        arefs = amessage.getHeader("References", null);
                        amsgid = amessage.getHeader("Message-Id", null);
                        break;
                    }

                if (arefs != null)
                    for (String ref : getReferences(arefs))
                        if (!result.contains(ref)) {
                            Log.i("rfc822 ref=" + ref);
                            result.add(ref);
                        }

                if (amsgid != null) {
                    String msgid = MimeUtility.unfold(amsgid);
                    if (!result.contains(msgid)) {
                        Log.i("rfc822 id=" + msgid);
                        result.add(msgid);
                    }
                }
            }
        }
    } catch (Throwable ex) {
        Log.w(ex);
    }

    return result.toArray(new String[0]);
}
 
Example 11
Source File: MessageHelper.java    From FairEmail with GNU General Public License v3.0 4 votes vote down vote up
String getInReplyTo() throws MessagingException {
    ensureMessage(false);

    String header = imessage.getHeader("In-Reply-To", null);
    return (header == null ? null : MimeUtility.unfold(header));
}
 
Example 12
Source File: MessageHelper.java    From FairEmail with GNU General Public License v3.0 4 votes vote down vote up
String getListUnsubscribe() throws MessagingException {
    ensureMessage(false);

    String list;
    try {
        // https://www.ietf.org/rfc/rfc2369.txt
        list = imessage.getHeader("List-Unsubscribe", null);
        if (list == null)
            return null;

        list = MimeUtility.unfold(list);
        list = decodeMime(list);

        if (list != null && list.startsWith("NO"))
            return null;

        String link = null;
        String mailto = null;
        for (String entry : list.split(",")) {
            entry = entry.trim();
            int lt = entry.indexOf("<");
            int gt = entry.lastIndexOf(">");
            if (lt >= 0 && gt > lt) {
                String unsubscribe = entry.substring(lt + 1, gt);
                Uri uri = Uri.parse(unsubscribe);
                String scheme = uri.getScheme();
                if (mailto == null && "mailto".equals(scheme))
                    mailto = unsubscribe;
                if (link == null && ("http".equals(scheme) || "https".equals(scheme)))
                    link = unsubscribe;
            }
        }

        if (link != null)
            return link;
        if (mailto != null)
            return mailto;

        Log.i(new IllegalArgumentException("List-Unsubscribe: " + list));
        return null;
    } catch (AddressException ex) {
        Log.w(ex);
        return null;
    }
}
 
Example 13
Source File: ImapConnection.java    From davmail with GNU General Public License v2.0 4 votes vote down vote up
protected void appendBodyStructure(StringBuilder buffer, MimePart bodyPart) throws IOException, MessagingException {
    String contentType = MimeUtility.unfold(bodyPart.getContentType());
    int slashIndex = contentType.indexOf('/');
    if (slashIndex < 0) {
        throw new DavMailException("EXCEPTION_INVALID_CONTENT_TYPE", contentType);
    }
    String type = contentType.substring(0, slashIndex).toUpperCase();
    buffer.append("(\"").append(type).append("\" \"");
    int semiColonIndex = contentType.indexOf(';');
    if (semiColonIndex < 0) {
        buffer.append(contentType.substring(slashIndex + 1).toUpperCase()).append("\" NIL");
    } else {
        // extended content type
        buffer.append(contentType.substring(slashIndex + 1, semiColonIndex).trim().toUpperCase()).append('\"');
        int charsetindex = contentType.indexOf("charset=");
        int nameindex = contentType.indexOf("name=");
        if (charsetindex >= 0 || nameindex >= 0) {
            buffer.append(" (");

            if (charsetindex >= 0) {
                buffer.append("\"CHARSET\" ");
                int charsetSemiColonIndex = contentType.indexOf(';', charsetindex);
                int charsetEndIndex;
                if (charsetSemiColonIndex > 0) {
                    charsetEndIndex = charsetSemiColonIndex;
                } else {
                    charsetEndIndex = contentType.length();
                }
                String charSet = contentType.substring(charsetindex + "charset=".length(), charsetEndIndex);
                if (!charSet.startsWith("\"")) {
                    buffer.append('"');
                }
                buffer.append(charSet.trim().toUpperCase());
                if (!charSet.endsWith("\"")) {
                    buffer.append('"');
                }
            }

            if (nameindex >= 0) {
                if (charsetindex >= 0) {
                    buffer.append(' ');
                }

                buffer.append("\"NAME\" ");
                int nameSemiColonIndex = contentType.indexOf(';', nameindex);
                int nameEndIndex;
                if (nameSemiColonIndex > 0) {
                    nameEndIndex = nameSemiColonIndex;
                } else {
                    nameEndIndex = contentType.length();
                }
                String name = contentType.substring(nameindex + "name=".length(), nameEndIndex).trim();
                if (!name.startsWith("\"")) {
                    buffer.append('"');
                }
                buffer.append(name.trim());
                if (!name.endsWith("\"")) {
                    buffer.append('"');
                }
            }
            buffer.append(')');
        } else {
            buffer.append(" NIL");
        }
    }
    int bodySize = getBodyPartSize(bodyPart);
    appendBodyStructureValue(buffer, bodyPart.getContentID());
    appendBodyStructureValue(buffer, bodyPart.getDescription());
    appendBodyStructureValue(buffer, bodyPart.getEncoding());
    appendBodyStructureValue(buffer, bodySize);
    if ("MESSAGE".equals(type) || "TEXT".equals(type)) {
        // line count not implemented in JavaMail, return fake line count
        appendBodyStructureValue(buffer, bodySize / 80);
    } else {
        // do not send line count for non text bodyparts
        appendBodyStructureValue(buffer, -1);
    }
    buffer.append(')');
}
 
Example 14
Source File: EnvelopeBuilder.java    From james-project with Apache License 2.0 4 votes vote down vote up
/**
 * Try to parse the addresses out of the header. If its not possible because
 * of a {@link ParseException} a null value is returned
 * 
 * @param message
 * @param headerName
 * @return addresses
 * @throws MailboxException
 */
private FetchResponse.Envelope.Address[] buildAddresses(Headers message, String headerName) throws MailboxException {
    final Header header = MessageResultUtils.getMatching(headerName, message.headers());
    FetchResponse.Envelope.Address[] results;
    if (header == null) {
        results = null;
    } else {

        // We need to unfold the header line.
        // See https://issues.apache.org/jira/browse/IMAP-154
        //
        // IMAP-Servers are advised to also replace tabs with single spaces while doing the unfolding. This is what javamails
        // unfold does. mime4j's unfold does strictly follow the rfc and so preserve them
        //
        // See IMAP-327 and https://mailman2.u.washington.edu/mailman/htdig/imap-protocol/2010-July/001271.html
        String value = MimeUtility.unfold(header.getValue());

        if ("".equals(value.trim())) {
            results = null;
        } else {

            AddressList addressList = LenientAddressParser.DEFAULT.parseAddressList(value);
            final int size = addressList.size();
            final List<FetchResponse.Envelope.Address> addresses = new ArrayList<>(size);
            for (Address address : addressList) {
                if (address instanceof Group) {
                    final Group group = (Group) address;
                    addAddresses(group, addresses);

                } else if (address instanceof Mailbox) {
                    final Mailbox mailbox = (Mailbox) address;
                    final FetchResponse.Envelope.Address mailboxAddress = buildMailboxAddress(mailbox);
                    addresses.add(mailboxAddress);

                } else {
                    LOGGER.warn("Unknown address type {}", address.getClass());
                }
            }

            results = addresses.toArray(FetchResponse.Envelope.Address[]::new);
            

        }
    }
    return results;
}