Java Code Examples for javax.mail.internet.MimeMessage#getHeader()

The following examples show how to use javax.mail.internet.MimeMessage#getHeader() . 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: BasicEmailService.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
protected void setRecipients(Map<RecipientType, InternetAddress[]> headerTo, MimeMessage msg)
		throws MessagingException
{
	if (headerTo != null)
	{
		if (msg.getHeader(EmailHeaders.TO) == null && headerTo.containsKey(RecipientType.TO))
		{
			msg.setRecipients(Message.RecipientType.TO, headerTo.get(RecipientType.TO));
		}
		if (msg.getHeader(EmailHeaders.CC) == null && headerTo.containsKey(RecipientType.CC))
		{
			msg.setRecipients(Message.RecipientType.CC, headerTo.get(RecipientType.CC));
		}
		if (headerTo.containsKey(RecipientType.BCC))
		{
			msg.setRecipients(Message.RecipientType.BCC, headerTo.get(RecipientType.BCC));
		}
	}
}
 
Example 2
Source File: GenericRegexMatcher.java    From james-project with Apache License 2.0 6 votes vote down vote up
@Override
public Collection<MailAddress> match(Mail mail) throws MessagingException {
    MimeMessage message = mail.getMessage();

    //Loop through all the patterns
    if (patterns != null) {
        for (Object[] pattern1 : patterns) {
            //Get the header name
            String headerName = (String) pattern1[0];
            //Get the patterns for that header
            Pattern pattern = (Pattern) pattern1[1];
            //Get the array of header values that match that
            String[] headers = message.getHeader(headerName);
            //Loop through the header values
            if (headers != null) {
                for (String header : headers) {
                    if (pattern.matcher(header).matches()) {
                        return mail.getRecipients();
                    }
                }
            }
        }
    }
    return null;
}
 
Example 3
Source File: MimeReader.java    From baleen with Apache License 2.0 6 votes vote down vote up
private void addPeopleToHeader(
    final MimeMessage mimeMessage,
    final String header,
    final int offset,
    final JCas jCas,
    final StringBuilder sb)
    throws MessagingException {
  final String[] people = mimeMessage.getHeader(header);
  if (people == null) {
    return;
  }

  Arrays.stream(people)
      .flatMap(p -> COMMA_SPLITTER.splitToList(p).stream())
      // TODO: might want to strip off any emails in <> here
      .forEach(p -> addPersonToHeaderBlock(p, offset, sb, jCas));
}
 
Example 4
Source File: BasicEmailService.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
protected void setRecipients(Map<RecipientType, InternetAddress[]> headerTo, MimeMessage msg)
		throws MessagingException
{
	if (headerTo != null)
	{
		if (msg.getHeader(EmailHeaders.TO) == null && headerTo.containsKey(RecipientType.TO))
		{
			msg.setRecipients(Message.RecipientType.TO, headerTo.get(RecipientType.TO));
		}
		if (msg.getHeader(EmailHeaders.CC) == null && headerTo.containsKey(RecipientType.CC))
		{
			msg.setRecipients(Message.RecipientType.CC, headerTo.get(RecipientType.CC));
		}
		if (headerTo.containsKey(RecipientType.BCC))
		{
			msg.setRecipients(Message.RecipientType.BCC, headerTo.get(RecipientType.BCC));
		}
	}
}
 
Example 5
Source File: ExchangeSession.java    From davmail with GNU General Public License v2.0 5 votes vote down vote up
protected void convertResentHeader(MimeMessage mimeMessage, String headerName) throws MessagingException {
    String[] resentHeader = mimeMessage.getHeader("Resent-" + headerName);
    if (resentHeader != null) {
        mimeMessage.removeHeader("Resent-" + headerName);
        mimeMessage.removeHeader(headerName);
        for (String value : resentHeader) {
            mimeMessage.addHeader(headerName, value);
        }
    }
}
 
Example 6
Source File: EmailTest.java    From commons-email with Apache License 2.0 5 votes vote down vote up
@Test
public void testFoldingHeaders() throws Exception
{
    email.setHostName(strTestMailServer);
    email.setSmtpPort(getMailServerPort());
    email.setFrom("[email protected]");
    email.addTo("[email protected]");
    email.setSubject("test mail");

    final String headerValue = "1234567890 1234567890 123456789 01234567890 123456789 0123456789 01234567890 01234567890";
    email.addHeader("X-LongHeader", headerValue);

    assertTrue(email.getHeaders().size() == 1);
    // the header should not yet be folded -> will be done by buildMimeMessage()
    assertFalse(email.getHeaders().get("X-LongHeader").contains("\r\n"));

    email.buildMimeMessage();

    final MimeMessage msg = email.getMimeMessage();
    msg.saveChanges();

    final String[] values = msg.getHeader("X-LongHeader");
    assertEquals(1, values.length);

    // the header should be split in two lines
    final String[] lines = values[0].split("\\r\\n");
    assertEquals(2, lines.length);

    // there should only be one line-break
    assertTrue(values[0].indexOf("\n") == values[0].lastIndexOf("\n"));
}
 
Example 7
Source File: HasHabeasWarrantMark.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Override
public Collection<MailAddress> match(Mail mail) throws MessagingException {
    MimeMessage message = mail.getMessage();

    //Loop through all the patterns
    for (String[] aWarrantMark : warrantMark) {
        try {
            String headerName = aWarrantMark[0];                      //Get the header name
            String requiredValue = aWarrantMark[1];                   //Get the required value
            String headerValue = message.getHeader(headerName, null);   //Get the header value(s)

            // We want an exact match, so only test the first value.
            // If there are multiple values, the header may be
            // (illegally) forged.  I'll leave it as an exercise to
            // others if they want to detect and report potentially
            // forged headers.

            if (!(requiredValue.equals(headerValue))) {
                return null;
            }
        } catch (Exception e) {
            LOGGER.info("Caught an exception while reading message", e);
            return null;            //if we get an exception, don't validate the mark
        }
    }

    // If we get here, all headers are present and match.
    return mail.getRecipients();
}
 
Example 8
Source File: FetchedFrom.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Override
public Collection<MailAddress> match(Mail mail) throws MessagingException {
    MimeMessage message = mail.getMessage();
    String fetchHeaderValue = message.getHeader(X_FETCHED_FROM, null);
    if (Objects.equal(fetchHeaderValue, getCondition())) {
        mail.getMessage().removeHeader(X_FETCHED_FROM);
        return mail.getRecipients();
    }
    return null;
}
 
Example 9
Source File: UseHeaderRecipients.java    From james-project with Apache License 2.0 5 votes vote down vote up
/**
 * Work through all the headers of the email with a matching name and
 * extract all the mail addresses as a collection of addresses.
 *
 * @param message the mail message to read
 * @param name    the header name as a String
 * @return the collection of MailAddress objects.
 */
private Collection<MailAddress> getHeaderMailAddresses(MimeMessage message, String name) throws MessagingException {
    if (isDebug) {
        LOGGER.debug("Checking {} headers", name);
    }
    String[] headers = message.getHeader(name);
    ImmutableList.Builder<MailAddress> addresses = ImmutableList.builder();

    if (headers != null) {
        for (String header : headers) {
           addresses.addAll(getMailAddressesFromHeaderLine(header));
        }
    }
    return addresses.build();
}
 
Example 10
Source File: MailUtils.java    From scada with MIT License 5 votes vote down vote up
/**
 * ����ʼ������ȼ�
 * @param msg �ʼ�����
 * @return 1(High):����  3:��ͨ(Normal)  5:��(Low)
 */ 
public static String getPriority(MimeMessage msg) throws MessagingException { 
    String priority = "��ͨ"; 
    String[] headers = msg.getHeader("X-Priority"); 
    if (headers != null) { 
        String headerPriority = headers[0]; 
        if (headerPriority.indexOf("1") != -1 || headerPriority.indexOf("High") != -1) 
            priority = "����"; 
        else if (headerPriority.indexOf("5") != -1 || headerPriority.indexOf("Low") != -1) 
            priority = "��"; 
        else 
            priority = "��ͨ"; 
    } 
    return priority; 
}
 
Example 11
Source File: MailEntityProcessor.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
private void addEnvelopeToDocument(Part part, Map<String,Object> row)
    throws MessagingException {
  MimeMessage mail = (MimeMessage) part;
  Address[] adresses;
  if ((adresses = mail.getFrom()) != null && adresses.length > 0) row.put(
      FROM, adresses[0].toString());
  
  List<String> to = new ArrayList<>();
  if ((adresses = mail.getRecipients(Message.RecipientType.TO)) != null) addAddressToList(
      adresses, to);
  if ((adresses = mail.getRecipients(Message.RecipientType.CC)) != null) addAddressToList(
      adresses, to);
  if ((adresses = mail.getRecipients(Message.RecipientType.BCC)) != null) addAddressToList(
      adresses, to);
  if (to.size() > 0) row.put(TO_CC_BCC, to);
  
  row.put(MESSAGE_ID, mail.getMessageID());
  row.put(SUBJECT, mail.getSubject());
  
  Date d = mail.getSentDate();
  if (d != null) {
    row.put(SENT_DATE, d);
  }
  
  List<String> flags = new ArrayList<>();
  for (Flags.Flag flag : mail.getFlags().getSystemFlags()) {
    if (flag == Flags.Flag.ANSWERED) flags.add(FLAG_ANSWERED);
    else if (flag == Flags.Flag.DELETED) flags.add(FLAG_DELETED);
    else if (flag == Flags.Flag.DRAFT) flags.add(FLAG_DRAFT);
    else if (flag == Flags.Flag.FLAGGED) flags.add(FLAG_FLAGGED);
    else if (flag == Flags.Flag.RECENT) flags.add(FLAG_RECENT);
    else if (flag == Flags.Flag.SEEN) flags.add(FLAG_SEEN);
  }
  flags.addAll(Arrays.asList(mail.getFlags().getUserFlags()));
  if (flags.size() == 0) flags.add(FLAG_NONE);
  row.put(FLAGS, flags);
  
  String[] hdrs = mail.getHeader("X-Mailer");
  if (hdrs != null) row.put(XMAILER, hdrs[0]);
}
 
Example 12
Source File: MimeMessageWrapper.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
public String[] getHeader(String header) {
    MimeMessage message = getMessage();
    try {
        return message.getHeader(header);
    } catch (MessagingException e) {
        Debug.logError(e, module);
        return null;
    }
}
 
Example 13
Source File: ExchangeSession.java    From davmail with GNU General Public License v2.0 5 votes vote down vote up
protected List<InternetAddress> getAllRecipients(MimeMessage mimeMessage) throws MessagingException {
    List<InternetAddress> recipientList = new ArrayList<>();
    for (String recipientHeader : RECIPIENT_HEADERS) {
        final String recipientHeaderValue = mimeMessage.getHeader(recipientHeader, ",");
        if (recipientHeaderValue != null) {
            // parse headers in non strict mode
            recipientList.addAll(Arrays.asList(InternetAddress.parseHeader(recipientHeaderValue, false)));
        }

    }
    return recipientList;
}
 
Example 14
Source File: BayesianAnalysis.java    From james-project with Apache License 2.0 4 votes vote down vote up
/**
 * Scans the mail and determines the spam probability.
 * 
 * @param mail
 *            The Mail message to be scanned.
 * @throws MessagingException
 *             if a problem arises
 */
@Override
public void service(Mail mail) throws MessagingException {

    try {
        MimeMessage message = mail.getMessage();

        if (ignoreLocalSender && isSenderLocal(mail)) {
            // ignore the message if the sender is local
            return;
        }

        String[] headerArray = message.getHeader(headerName);
        // ignore the message if already analyzed
        if (headerArray != null && headerArray.length > 0) {
            return;
        }

        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        double probability;

        if (message.getSize() < getMaxSize()) {
            message.writeTo(baos);
            probability = analyzer.computeSpamProbability(new BufferedReader(new StringReader(baos.toString())));
        } else {
            probability = 0.0;
        }

        mail.setAttribute(new Attribute(MAIL_ATTRIBUTE_NAME, AttributeValue.of(probability)));
        message.setHeader(headerName, Double.toString(probability));

        DecimalFormat probabilityForm = (DecimalFormat) DecimalFormat.getInstance();
        probabilityForm.applyPattern("##0.##%");
        String probabilityString = probabilityForm.format(probability);

        String senderString = mail.getMaybeSender().asString("null");
        if (probability > 0.1) {
            final Collection<MailAddress> recipients = mail.getRecipients();
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug(headerName + ": " + probabilityString + "; From: " + senderString + "; Recipient(s): " + getAddressesString(recipients));
            }

            // Check if we should tag the subject
            if (tagSubject) {
                appendToSubject(message, " [" + probabilityString + (probability > 0.9 ? " SPAM" : " spam") + "]");
            }
        }

        saveChanges(message);

    } catch (Exception e) {
        LOGGER.error("Exception: {}", e.getMessage(), e);
        throw new MessagingException("Exception thrown", e);
    }
}
 
Example 15
Source File: CompareNumericHeaderValue.java    From james-project with Apache License 2.0 4 votes vote down vote up
@Override
public Collection<MailAddress> match(Mail mail) throws MessagingException {
    if (headerName == null) {
        // should never get here
        throw new IllegalStateException("Null headerName");
    }
    
    MimeMessage message = mail.getMessage();
    
    String [] headerArray = message.getHeader(headerName);
    if (headerArray != null && headerArray.length > 0) {
        try {
            int comparison = Double.valueOf(headerArray[0].trim()).compareTo(headerValue);
            switch (comparisonOperator) {
                case LT:
                    if (comparison < 0) {
                        return mail.getRecipients();
                    }
                    break;
                case LE:
                    if (comparison <= 0) {
                        return mail.getRecipients();
                    }
                    break;
                case EQ:
                    if (comparison == 0) {
                        return mail.getRecipients();
                    }
                    break;
                case GE:
                    if (comparison >= 0) {
                        return mail.getRecipients();
                    }
                    break;
                case GT:
                    if (comparison > 0) {
                        return mail.getRecipients();
                    }
                    break;
                default:
                    // should never get here
                    throw new IllegalStateException("Unknown comparisonOperator" + comparisonOperator);
            }
        } catch (NumberFormatException nfe) {
            throw new MessagingException("Bad header value found in message: \"" + headerArray[0] + "\"", nfe);
        }
    }
    
    return null;
}
 
Example 16
Source File: WhiteListManager.java    From james-project with Apache License 2.0 4 votes vote down vote up
private void sendReplyFromPostmaster(Mail mail, String stringContent) {
    try {
        MailAddress notifier = getMailetContext().getPostmaster();

        MailAddress senderMailAddress = mail.getMaybeSender().get();

        MimeMessage message = mail.getMessage();
        // Create the reply message
        MimeMessage reply = new MimeMessage(Session.getDefaultInstance(System.getProperties(), null));

        // Create the list of recipients in the Address[] format
        InternetAddress[] rcptAddr = new InternetAddress[1];
        rcptAddr[0] = senderMailAddress.toInternetAddress();
        reply.setRecipients(Message.RecipientType.TO, rcptAddr);

        // Set the sender...
        reply.setFrom(notifier.toInternetAddress());

        // Create the message body
        MimeMultipart multipart = new MimeMultipart();
        // Add message as the first mime body part
        MimeBodyPart part = new MimeBodyPart();
        part.setContent(stringContent, "text/plain");
        part.setHeader(RFC2822Headers.CONTENT_TYPE, "text/plain");
        multipart.addBodyPart(part);

        reply.setContent(multipart);
        reply.setHeader(RFC2822Headers.CONTENT_TYPE, multipart.getContentType());

        // Create the list of recipients in our MailAddress format
        Set<MailAddress> recipients = new HashSet<>();
        recipients.add(senderMailAddress);

        // Set additional headers
        if (reply.getHeader(RFC2822Headers.DATE) == null) {
            reply.setHeader(RFC2822Headers.DATE, DateFormats.RFC822_DATE_FORMAT.format(LocalDateTime.now()));
        }
        String subject = message.getSubject();
        if (subject == null) {
            subject = "";
        }
        if (subject.indexOf("Re:") == 0) {
            reply.setSubject(subject);
        } else {
            reply.setSubject("Re:" + subject);
        }
        reply.setHeader(RFC2822Headers.IN_REPLY_TO, message.getMessageID());

        // Send it off...
        getMailetContext().sendMail(notifier, recipients, reply);
    } catch (Exception e) {
        LOGGER.error("Exception found sending reply", e);
    }
}
 
Example 17
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]);
}