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

The following examples show how to use javax.mail.internet.MimeMessage#getMessageID() . 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: Mail.java    From camunda-bpm-mail with Apache License 2.0 6 votes vote down vote up
public static Mail from(Message message) throws MessagingException, IOException {
  Mail mail = new Mail();

  mail.from = InternetAddress.toString(message.getFrom());
  mail.to =  InternetAddress.toString(message.getRecipients(RecipientType.TO));
  mail.cc = InternetAddress.toString(message.getRecipients(RecipientType.CC));

  mail.subject = message.getSubject();
  mail.sentDate = message.getSentDate();
  mail.receivedDate = message.getReceivedDate();

  mail.messageNumber = message.getMessageNumber();

  if (message instanceof MimeMessage) {
    MimeMessage mimeMessage = (MimeMessage) message;
    // extract more informations
    mail.messageId = mimeMessage.getMessageID();
  }

  processMessageContent(message, mail);

  return mail;
}
 
Example 2
Source File: DefaultClosableSmtpConnection.java    From smtp-connection-pool with Apache License 2.0 6 votes vote down vote up
private void doSend(MimeMessage mimeMessage, Address[] recipients) throws MessagingException {

    try {
      if (mimeMessage.getSentDate() == null) {
        mimeMessage.setSentDate(new Date());
      }
      String messageId = mimeMessage.getMessageID();
      mimeMessage.saveChanges();
      if (messageId != null) {
        // Preserve explicitly specified message id...
        mimeMessage.setHeader(HEADER_MESSAGE_ID, messageId);
      }
      delegate.sendMessage(mimeMessage, recipients);
    } catch (Exception e) {
      // TODO: An exception can be sent because the recipient is invalid, ie. not because the connection is invalid
      // TODO: Invalidate based on the MessagingException subclass / cause: IOException
      if (invalidateConnectionOnException) {
        invalidate();
      }
      throw e;
    }
  }
 
Example 3
Source File: ExchangeSession.java    From davmail with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Send message in reader to recipients.
 * Detect visible recipients in message body to determine bcc recipients
 *
 * @param rcptToRecipients recipients list
 * @param mimeMessage      mime message
 * @throws IOException        on error
 * @throws MessagingException on error
 */
public void sendMessage(List<String> rcptToRecipients, MimeMessage mimeMessage) throws IOException, MessagingException {
    // detect duplicate send command
    String messageId = mimeMessage.getMessageID();
    if (lastSentMessageId != null && lastSentMessageId.equals(messageId)) {
        LOGGER.debug("Dropping message id " + messageId + ": already sent");
        return;
    }
    lastSentMessageId = messageId;

    convertResentHeader(mimeMessage, "From");
    convertResentHeader(mimeMessage, "To");
    convertResentHeader(mimeMessage, "Cc");
    convertResentHeader(mimeMessage, "Bcc");
    convertResentHeader(mimeMessage, "Message-Id");

    // do not allow send as another user on Exchange 2003
    if ("Exchange2003".equals(serverVersion) || Settings.getBooleanProperty("davmail.smtpStripFrom", false)) {
        mimeMessage.removeHeader("From");
    }

    // remove visible recipients from list
    Set<String> visibleRecipients = new HashSet<>();
    List<InternetAddress> recipients = getAllRecipients(mimeMessage);
    for (InternetAddress address : recipients) {
        visibleRecipients.add((address.getAddress().toLowerCase()));
    }
    for (String recipient : rcptToRecipients) {
        if (!visibleRecipients.contains(recipient.toLowerCase())) {
            mimeMessage.addRecipient(javax.mail.Message.RecipientType.BCC, new InternetAddress(recipient));
        }
    }
    sendMessage(mimeMessage);

}
 
Example 4
Source File: MimeMessageWrapper.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
public String getMessageId() {
    MimeMessage message = getMessage();
    try {
        return message.getMessageID();
    } catch (MessagingException e) {
        Debug.logError(e, module);
        return null;
    }
}
 
Example 5
Source File: SMTPHandler.java    From holdmail with Apache License 2.0 5 votes vote down vote up
@Override
public void done() {

    try {

        Session s = Session.getDefaultInstance(new Properties());
        MimeMessage mimeMsg = new MimeMessage(s, new ByteArrayInputStream(data));

        // set any data parse the mimemessage itself
        MessageHeaders headers = getHeaders(mimeMsg);

        Message message = new Message(0,
                mimeMsg.getMessageID(),
                DecoderUtil.decodeEncodedWords(headers.get("Subject"), Charsets.UTF_8),
                this.senderEmail,
                new Date(),
                senderHost,
                this.data.length,
                IOUtils.toString(data, StandardCharsets.UTF_8.name()),
                this.recipients,
                headers
        );

        messageService.saveMessage(message);

        logger.info(String.format("Stored SMTP message '%s' parse %s to: %s",
                message.getIdentifier(),
                message.getSenderEmail(),
                StringUtils.join(message.getRecipients(), ","))
        );

    } catch (Exception e) {

        logger.error("Couldn't handle message: " + e.getMessage(), e);

    }

}
 
Example 6
Source File: BayesianAnalysis.java    From james-project with Apache License 2.0 5 votes vote down vote up
/**
 * Saves changes resetting the original message id.
 */
private void saveChanges(MimeMessage message) throws MessagingException {
    String messageId = message.getMessageID();
    message.saveChanges();
    if (messageId != null) {
        message.setHeader(RFC2822Headers.MESSAGE_ID, messageId);
    }
}
 
Example 7
Source File: ClamAVScan.java    From james-project with Apache License 2.0 5 votes vote down vote up
/**
 * Saves changes resetting the original message id.
 *
 * @param message the message to save
 */
protected final void saveChanges(MimeMessage message) throws MessagingException {
    String messageId = message.getMessageID();
    message.saveChanges();
    if (messageId != null) {
        message.setHeader(RFC2822Headers.MESSAGE_ID, messageId);
    }
}
 
Example 8
Source File: HeadersToHTTP.java    From james-project with Apache License 2.0 5 votes vote down vote up
private HashSet<NameValuePair> getNameValuePairs(MimeMessage message) throws UnsupportedEncodingException, MessagingException {

        // to_address
        // from
        // reply to
        // subject

        HashSet<NameValuePair> pairs = new HashSet<>();

        if (message != null) {
            if (message.getSender() != null) {
                pairs.add(new BasicNameValuePair("from", message.getSender().toString()));
            }
            if (message.getReplyTo() != null) {
                pairs.add(new BasicNameValuePair("reply_to", Arrays.toString(message.getReplyTo())));
            }
            if (message.getMessageID() != null) {
                pairs.add(new BasicNameValuePair("message_id", message.getMessageID()));
            }
            if (message.getSubject() != null) {
                pairs.add(new BasicNameValuePair("subject", message.getSubject()));
            }
            pairs.add(new BasicNameValuePair("size", Integer.toString(message.getSize())));
        }

        pairs.add(new BasicNameValuePair(parameterKey, parameterValue));

        return pairs;
    }
 
Example 9
Source File: MimeMessageUtil.java    From james-project with Apache License 2.0 5 votes vote down vote up
/**
 * 
 * @param message
 * @param headerOs
 * @param bodyOs
 * @param ignoreList
 * @throws MessagingException
 * @throws IOException
 * @throws UnsupportedDataTypeException
 */
public static void writeToInternal(MimeMessage message, OutputStream headerOs, OutputStream bodyOs, String[] ignoreList) throws MessagingException, IOException {
    if (message.getMessageID() == null) {
        message.saveChanges();
    }

    writeHeadersTo(message, headerOs, ignoreList);

    // Write the body to the output stream
    writeMessageBodyTo(message, bodyOs);
}
 
Example 10
Source File: BayesianAnalysisFeeder.java    From james-project with Apache License 2.0 4 votes vote down vote up
/**
 * Scans the mail and updates the token frequencies in the database.
 * 
 * The method is synchronized in order to avoid too much database locking,
 * as thousands of rows may be updated just for one message fed.
 * 
 * @param mail
 *            The Mail message to be scanned.
 */
@Override
public void service(Mail mail) {
    boolean dbUpdated = false;

    mail.setState(Mail.GHOST);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    Connection conn = null;

    try {

        MimeMessage message = mail.getMessage();

        String messageId = message.getMessageID();

        if (message.getSize() > getMaxSize()) {
            LOGGER.debug("{} Feeding HAM/SPAM ignored because message size > {}: {}", messageId, getMaxSize(), message.getSize());
            return;
        }

        clearAllHeaders(message);

        message.writeTo(baos);

        BufferedReader br = new BufferedReader(new StringReader(baos.toString()));

        // this is synchronized to avoid concurrent update of the corpus
        synchronized (JDBCBayesianAnalyzer.DATABASE_LOCK) {

            conn = datasource.getConnection();

            if (conn.getAutoCommit()) {
                conn.setAutoCommit(false);
            }

            dbUpdated = true;

            // Clear out any existing word/counts etc..
            analyzer.clear();

            if ("ham".equalsIgnoreCase(feedType)) {
                LOGGER.debug("{} Feeding HAM", messageId);
                // Process the stream as ham (not spam).
                analyzer.addHam(br);

                // Update storage statistics.
                analyzer.updateHamTokens(conn);
            } else {
                LOGGER.debug("{} Feeding SPAM", messageId);
                // Process the stream as spam.
                analyzer.addSpam(br);

                // Update storage statistics.
                analyzer.updateSpamTokens(conn);
            }

            // Commit our changes if necessary.
            if (conn != null && dbUpdated && !conn.getAutoCommit()) {
                conn.commit();
                dbUpdated = false;
                LOGGER.debug("{} Training ended successfully", messageId);
                JDBCBayesianAnalyzer.touchLastDatabaseUpdateTime();
            }

        }

    } catch (java.sql.SQLException se) {
        LOGGER.error("SQLException: ", se);
    } catch (java.io.IOException ioe) {
        LOGGER.error("IOException: ", ioe);
    } catch (javax.mail.MessagingException me) {
        LOGGER.error("MessagingException: ", me);
    } finally {
        // Rollback our changes if necessary.
        try {
            if (conn != null && dbUpdated && !conn.getAutoCommit()) {
                conn.rollback();
                dbUpdated = false;
            }
        } catch (Exception e) {
            LOGGER.error("Failed to rollback after last error.", e);
        }
        theJDBCUtil.closeJDBCConnection(conn);
    }
}
 
Example 11
Source File: AbstractSign.java    From james-project with Apache License 2.0 4 votes vote down vote up
/**
 * Service does the hard work, and signs
 *
 * @param mail the mail to sign
 * @throws MessagingException if a problem arises signing the mail
 */
@Override
public void service(Mail mail) throws MessagingException {
    
    try {
        if (!isOkToSign(mail)) {
            return;
        }
        
        MimeBodyPart wrapperBodyPart = getWrapperBodyPart(mail);
        
        MimeMessage originalMessage = mail.getMessage();
        
        // do it
        MimeMultipart signedMimeMultipart;
        if (wrapperBodyPart != null) {
            signedMimeMultipart = getKeyHolder().generate(wrapperBodyPart);
        } else {
            signedMimeMultipart = getKeyHolder().generate(originalMessage);
        }
        
        MimeMessage newMessage = new MimeMessage(Session.getDefaultInstance(System.getProperties(),
        null));
        Enumeration<String> headerEnum = originalMessage.getAllHeaderLines();
        while (headerEnum.hasMoreElements()) {
            newMessage.addHeaderLine(headerEnum.nextElement());
        }
        
        newMessage.setSender(new InternetAddress(getKeyHolder().getSignerAddress(), getSignerName()));
  
        if (isRebuildFrom()) {
            // builds a new "mixed" "From:" header
            InternetAddress modifiedFromIA = new InternetAddress(getKeyHolder().getSignerAddress(), mail.getMaybeSender().asString());
            newMessage.setFrom(modifiedFromIA);
            
            // if the original "ReplyTo:" header is missing sets it to the original "From:" header
            newMessage.setReplyTo(originalMessage.getReplyTo());
        }
        
        newMessage.setContent(signedMimeMultipart, signedMimeMultipart.getContentType());
        String messageId = originalMessage.getMessageID();
        newMessage.saveChanges();
        if (messageId != null) {
            newMessage.setHeader(RFC2822Headers.MESSAGE_ID, messageId);
        }
        
        mail.setMessage(newMessage);
        
        // marks this mail as server-signed
        mail.setAttribute(new Attribute(SMIMEAttributeNames.SMIME_SIGNING_MAILET, AttributeValue.of(this.getClass().getName())));
        // it is valid for us by definition (signed here by us)
        mail.setAttribute(new Attribute(SMIMEAttributeNames.SMIME_SIGNATURE_VALIDITY, AttributeValue.of("valid")));
        
        // saves the trusted server signer address
        // warning: should be same as the mail address in the certificate, but it is not guaranteed
        mail.setAttribute(new Attribute(SMIMEAttributeNames.SMIME_SIGNER_ADDRESS, AttributeValue.of(getKeyHolder().getSignerAddress())));
        
        if (isDebug()) {
            LOGGER.debug("Message signed, reverse-path: {}, Id: {}", mail.getMaybeSender().asString(), messageId);
        }
        
    } catch (MessagingException me) {
        LOGGER.error("MessagingException found - could not sign!", me);
        throw me;
    } catch (Exception e) {
        LOGGER.error("Exception found", e);
        throw new MessagingException("Exception thrown - could not sign!", e);
    }
    
}