Example usage for javax.mail.internet MimeMessage getHeader

List of usage examples for javax.mail.internet MimeMessage getHeader

Introduction

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

Prototype

@Override
public String getHeader(String name, String delimiter) throws MessagingException 

Source Link

Document

Get all the headers for this header name, returned as a single String, with headers separated by the delimiter.

Usage

From source file:com.zimbra.cs.mime.Mime.java

/** Returns the value of the <tt>From</tt> header.  If not available,
 *  returns the value of the <tt>Sender</tt> header.  Returns an empty
 *  {@code String} if neither header is available. */
public static String getSender(MimeMessage mm) {
    String sender = null;//from   w  w w .j  av a2 s .  c o  m
    try {
        sender = mm.getHeader("From", null);
    } catch (MessagingException e) {
    }
    if (sender == null) {
        try {
            sender = mm.getHeader("Sender", null);
        } catch (MessagingException e) {
        }
    }
    if (sender == null) {
        sender = "";
    } else if (sender.endsWith("<>")) { // Bug #47492
        sender = sender.replaceAll("<>$", "").trim();
    }
    return sender;
}

From source file:com.zimbra.cs.mime.Mime.java

public static InternetAddress[] parseAddressHeader(MimeMessage mm, String headerName, boolean expandGroups) {
    try {/* w  ww . j  a v a2 s.c  o  m*/
        return parseAddressHeader(mm.getHeader(headerName, ","), expandGroups);
    } catch (MessagingException e) {
        return NO_ADDRESSES;
    }
}

From source file:mitm.common.mail.repository.hibernate.MailRepositoryItemEntity.java

private void initFrom(MimeMessage message) {
    try {/*from w w  w  .  j ava 2 s . c  o m*/
        String decodedFrom = null;

        try {
            decodedFrom = StringUtils.join(
                    EmailAddressUtils.addressesToStrings(message.getFrom(), true /* mime decode */), ", ");
        } catch (MessagingException e) {
            /*
             * Fallback to raw headers
             */
            decodedFrom = message.getHeader("from", ", ");
        }

        fromHeader = StringUtils.abbreviate(decodedFrom, FROM_MAX_LENGTH);
    } catch (MessagingException e) {
        logger.debug("Error getting from.", e);
    }
}

From source file:mitm.common.mail.MailUtilsTest.java

@Test
public void testConvert8BitTo7BitSimpleText() throws IOException, MessagingException {
    MimeMessage message = loadMessage("8bit-text.eml");

    assertEquals("8bIt", message.getEncoding());

    assertTrue(MailUtils.convertTo7Bit(message));

    message.saveChanges();/*from www  . ja  v  a2s.c om*/

    assertEquals("quoted-printable", message.getEncoding());

    MailUtils.validateMessage(message);

    File file = new File("test/tmp/testConvert8BitTo7BitSimpleText.eml");

    MailUtils.writeMessage(message, file);

    assertEquals("from 8bit to quoted-printable by Djigzo", message.getHeader("X-MIME-Autoconverted", ","));
}

From source file:immf.SendMailBridge.java

/**
 * SMTP???????//from  ww w  .j  av  a  2  s .co m
 * @param msg
 * @throws IOException
 */
public void receiveMail(MyWiserMessage msg) throws IOException {
    try {
        SenderMail senderMail = new SenderMail();

        log.info("==== SMTP???????====");
        log.info("From       " + msg.getEnvelopeSender());
        log.info("Recipients  " + msg.getEnvelopeReceiver());

        MimeMessage mime = msg.getMimeMessage();

        String messageId = mime.getHeader("Message-ID", null);
        log.info("messageID  " + messageId);
        List<String> recipients;
        if (messageId != null && receivedMessageTable != null) {
            synchronized (receivedMessageTable) {
                recipients = receivedMessageTable.get(messageId);
                if (recipients != null) {
                    recipients.addAll(msg.getEnvelopeReceiver());
                    log.info("Duplicated message ignored");
                    return;
                }

                recipients = msg.getEnvelopeReceiver();
                receivedMessageTable.put(messageId, recipients);
                receivedMessageTable.wait(this.duplicationCheckTimeSec * 1000);
                receivedMessageTable.remove(messageId);
            }
        } else {
            recipients = msg.getEnvelopeReceiver();
        }

        List<InternetAddress> to = getRecipients(mime, "To");
        List<InternetAddress> cc = getRecipients(mime, "Cc");
        List<InternetAddress> bcc = getBccRecipients(recipients, to, cc);

        int maxRecipients = MaxRecipient;
        if (this.alwaysBcc != null) {
            log.debug("add alwaysbcc " + this.alwaysBcc);
            bcc.add(new InternetAddress(this.alwaysBcc));
        }
        log.info("To   " + StringUtils.join(to, " / "));
        log.info("cc   " + StringUtils.join(cc, " / "));
        log.info("bcc   " + StringUtils.join(bcc, " / "));

        senderMail.setTo(to);
        senderMail.setCc(cc);
        senderMail.setBcc(bcc);

        if (maxRecipients < (to.size() + cc.size() + bcc.size())) {
            log.warn("??????i.net???5??");
            throw new IOException("Too Much Recipients");
        }

        String contentType = mime.getContentType().toLowerCase();
        log.info("ContentType:" + contentType);

        String charset = (new ContentType(contentType)).getParameter("charset");
        log.info("charset:" + charset);

        String mailer = mime.getHeader("X-Mailer", null);
        log.info("mailer  " + mailer);

        String subject = mime.getHeader("Subject", null);
        log.info("subject  " + subject);
        if (subject != null)
            subject = this.charConv.convertSubject(subject);
        log.debug(" conv " + subject);

        if (this.useGoomojiSubject) {
            String goomojiSubject = mime.getHeader("X-Goomoji-Subject", null);
            if (goomojiSubject != null)
                subject = this.googleCharConv.convertSubject(goomojiSubject);
        }

        boolean editRe = false;
        if (this.editDocomoSubjectPrefix) {
            for (InternetAddress addr : to) {
                String[] toString = addr.getAddress().split("@", 2);
                if (subject != null && toString[1].equals("docomo.ne.jp")) {
                    editRe = true;
                }
            }
        }
        if (editRe) {
            if (subject.matches("^R[eE]: ?R[eE].*$")) {
                log.info("?subject: " + subject);
                String reCounterStr = subject.replaceAll("^R[eE]: ?R[eE](\\d*):.*$", "$1");
                int reCounter = 2;
                if (!reCounterStr.isEmpty()) {
                    reCounter = Integer.parseInt(reCounterStr);
                    reCounter++;
                }
                subject = subject.replaceAll("^R[eE]: ?R[eE]\\d*:", "Re" + Integer.toString(reCounter) + ":");
                log.info("subject: " + subject);
            }
        }

        senderMail.setSubject(subject);

        Object content = mime.getContent();
        if (content instanceof String) {
            // 
            String strContent = (String) content;
            if (contentType.toLowerCase().startsWith("text/html")) {
                log.info("Single html part " + strContent);
                strContent = this.charConv.convert(strContent, charset);
                log.debug(" conv " + strContent);
                senderMail.setHtmlContent(strContent);
            } else {
                log.info("Single plainText part " + strContent);
                strContent = this.charConv.convert(strContent, charset);
                log.debug(" conv " + strContent);
                senderMail.setPlainTextContent(strContent);
            }
        } else if (content instanceof Multipart) {
            Multipart mp = (Multipart) content;
            parseMultipart(senderMail, mp, getSubtype(contentType), null);
            if (senderMail.getHtmlContent() == null && senderMail.getHtmlWorkingContent() != null) {
                senderMail.setHtmlContent(senderMail.getHtmlWorkingContent());
            }

        } else {
            log.warn("? " + content.getClass().getName());
            throw new IOException("Unsupported type " + content.getClass().getName() + ".");
        }

        if (stripAppleQuote) {
            Util.stripAppleQuotedLines(senderMail);
        }
        Util.stripLastEmptyLines(senderMail);

        log.info("Content  " + mime.getContent());
        log.info("====");

        if (this.sendAsync) {
            // ??
            // ?????OK?
            this.picker.add(senderMail);
        } else {
            // ??????
            this.client.sendMail(senderMail, this.forcePlainText);
            if (isForwardSent) {
                status.setNeedConnect();
            }
        }

    } catch (IOException e) {
        log.warn("Bad Mail Received.", e);
        throw e;
    } catch (Exception e) {
        log.error("ReceiveMail Error.", e);
        throw new IOException("ReceiveMail Error." + e.getMessage(), e);
    }
}

From source file:com.duroty.utils.mail.MessageUtilities.java

/**
 * Determin if the message is high-priority.
 *
 * @param message the message to examine
 *
 * @return true if the message is high-priority
 *
 * @throws MessagingException DOCUMENT ME!
 *//*w  w  w.  ja v  a2s .c  om*/
public static boolean isHighPriority(Message message) throws MessagingException {
    if (message instanceof MimeMessage) {
        MimeMessage xmime = (MimeMessage) message;
        String xpriority = xmime.getHeader("Importance", null);

        if (xpriority != null) {
            xpriority = xpriority.toLowerCase();

            if (xpriority.indexOf("high") == 0) {
                return true;
            }
        }

        // X Standard: X-Priority: 1 | 2 | 3 | 4 | 5 (lowest)
        xpriority = xmime.getHeader("X-Priority", null);

        if (xpriority != null) {
            xpriority = xpriority.toLowerCase();

            if ((xpriority.indexOf("1") == 0) || (xpriority.indexOf("2") == 0)) {
                return true;
            }
        }
    }

    return false;
}

From source file:com.duroty.utils.mail.MessageUtilities.java

/**
 * Determin if the message is low-priority.
 *
 * @param message the message to examine
 *
 * @return true if the message is low-priority
 *
 * @throws MessagingException DOCUMENT ME!
 *///from  w ww  .  ja v a2s  .  c  o m
public static boolean isLowPriority(Message message) throws MessagingException {
    if (message instanceof MimeMessage) {
        MimeMessage xmime = (MimeMessage) message;
        String xpriority = xmime.getHeader("Importance", null);

        if (xpriority != null) {
            xpriority = xpriority.toLowerCase();

            if (xpriority.indexOf("low") == 0) {
                return true;
            }
        }

        // X Standard: X-Priority: 1 | 2 | 3 | 4 | 5 (lowest)
        xpriority = xmime.getHeader("X-Priority", null);

        if (xpriority != null) {
            xpriority = xpriority.toLowerCase();

            if ((xpriority.indexOf("4") == 0) || (xpriority.indexOf("5") == 0)) {
                return true;
            }
        }
    }

    return false;
}

From source file:mitm.common.security.smime.SMIMEBuilderImplTest.java

private static void checkForEmbeddedHeaders(MimeMessage message) throws MessagingException {
    // the message should contain the signed from, to and subject
    assertEquals("<test@example.com>", message.getHeader("from", ","));
    assertEquals("<test@example.com>", message.getHeader("to", ","));
    assertEquals("normal message with attachment", message.getHeader("subject", ","));
}

From source file:mitm.common.security.smime.SMIMEBuilderImplTest.java

private static void checkForSourceHeaders(MimeMessage message) throws MessagingException {
    // the message should contain the signed from, to and subject
    assertEquals("<test@example.com>", message.getHeader("from", ","));
    assertEquals("<test@example.com>", message.getHeader("to", ","));
    assertEquals("normal message with attachment", message.getHeader("subject", ","));
    assertEquals("1.0", message.getHeader("MIME-Version", ","));
    assertEquals("3", message.getHeader("X-Priority", ","));
    assertEquals("Normal", message.getHeader("X-MSMail-Priority", ","));
    assertEquals("Produced By Microsoft MimeOLE V6.00.2800.1896", message.getHeader("X-MimeOLE", ","));
    assertEquals("test 1,test 2", message.getHeader("X-Test", ","));
    assertEquals("test 3", message.getHeader("X-Test-a", ","));
    assertEquals("test 4", message.getHeader("X-Test-b", ","));
}

From source file:com.zimbra.cs.util.SpamExtract.java

private static void writeAttachedMessages(MimeMessage mm, File outdir, String msgUri)
        throws IOException, MessagingException {
    // Not raw - ignore the spam report and extract messages that are in attachments...
    if (!(mm.getContent() instanceof MimeMultipart)) {
        LOG.warn("Spam/notspam messages must have attachments (skipping " + msgUri + ")");
        return;//ww  w .  j  a va  2 s  .com
    }

    MimeMultipart mmp = (MimeMultipart) mm.getContent();
    int nAttachments = mmp.getCount();
    boolean foundAtleastOneAttachedMessage = false;
    for (int i = 0; i < nAttachments; i++) {
        BodyPart bp = mmp.getBodyPart(i);
        if (!bp.isMimeType("message/rfc822")) {
            // Let's ignore all parts that are not messages.
            continue;
        }
        foundAtleastOneAttachedMessage = true;
        Part msg = (Part) bp.getContent(); // the actual message
        File file = new File(outdir, mOutputPrefix + "-" + mExtractIndex++);
        OutputStream os = null;
        try {
            os = new BufferedOutputStream(new FileOutputStream(file));
            if (msg instanceof MimeMessage) {
                //bug 74435 clone into newMsg so our parser has a chance to handle headers which choke javamail
                ZMimeMessage newMsg = new ZMimeMessage((MimeMessage) msg);
                newMsg.writeTo(os);
            } else {
                msg.writeTo(os);
            }
        } finally {
            os.close();
        }
        if (verbose)
            LOG.info("Wrote: " + file);
    }

    if (!foundAtleastOneAttachedMessage) {
        String msgid = mm.getHeader("Message-ID", " ");
        LOG.warn("message uri=" + msgUri + " message-id=" + msgid + " had no attachments");
    }
}