Search in sources :

Example 26 with MimeMessage

use of javax.mail.internet.MimeMessage in project nhin-d by DirectProject.

the class NotificationSuppressor method service.

/**
	 * {@inheritDoc}
	 */
@Override
public void service(Mail mail) throws MessagingException {
    boolean suppress = false;
    final MimeMessage msg = mail.getMessage();
    final NHINDAddressCollection recipients = getMailRecipients(mail);
    final NHINDAddress sender = getMailSender(mail);
    final Tx txToTrack = getTxToTrack(msg, sender, recipients);
    if (txToTrack != null) {
        try {
            // first check if this a MDN processed message and if the consume processed flag is turned on
            final TxDetail detail = txToTrack.getDetail(TxDetailType.DISPOSITION);
            if (consumeMDNProcessed && txToTrack.getMsgType() == TxMessageType.MDN && detail != null && detail.getDetailValue().contains(MDNStandard.Disposition_Processed))
                suppress = true;
            else // if the first rule does not apply, then go to the tx Service to see if the message should be suppressed
            if (txService != null && txToTrack != null && txService.suppressNotification(txToTrack))
                suppress = true;
        } catch (ServiceException e) {
            // failing to call the txService should not result in an exception being thrown
            // from this service.
            LOGGER.warn("Failed to get notification suppression status from service.  Message will assume to not need supressing.");
        }
    }
    if (suppress)
        mail.setState(Mail.GHOST);
}
Also used : NHINDAddress(org.nhindirect.stagent.NHINDAddress) Tx(org.nhindirect.common.tx.model.Tx) ServiceException(org.nhindirect.common.rest.exceptions.ServiceException) MimeMessage(javax.mail.internet.MimeMessage) NHINDAddressCollection(org.nhindirect.stagent.NHINDAddressCollection) TxDetail(org.nhindirect.common.tx.model.TxDetail)

Example 27 with MimeMessage

use of javax.mail.internet.MimeMessage in project nhin-d by DirectProject.

the class DefaultSmtpAgent method processMessage.

/**
	 * Processes an message from an SMTP stack.  The bridge component between the SMTP stack and the SMTP agent is responsible for
	 * extracting the message, the recipient list, and the sender.  In some cases, the routing headers may have different information than
	 * what is populated in the SMTP MAIL FROM and RCTP TO headers.  In these cases, the SMTP headers should be favored over the routing
	 * headers in the message and passed as the recipient collection and sender to this method.
	 * @param message The message in the SMTP envelope.
	 * @param recipients The recipients of the message.  The RCTP TO headers should be used over the message routing headers.
	 * @param sender The send of the message. The MAIL FROM header should be used over the From: routing header in the message.
	 */
public MessageProcessResult processMessage(MimeMessage message, NHINDAddressCollection recipients, NHINDAddress sender) {
    GatewayState.getInstance().lockForProcessing();
    try {
        LOGGER.trace("Entering processMessage(MimeMessage, NHINDAddressCollection, NHINDAddress");
        MessageProcessResult retVal = null;
        verifyInitialized();
        preProcessMessage(message, sender);
        Collection<NHINDAddress> originalRecipList = new ArrayList<NHINDAddress>(recipients);
        DefaultMessageEnvelope envelopeToProcess = null;
        try {
            envelopeToProcess = new DefaultMessageEnvelope(new Message(message), recipients, sender);
            envelopeToProcess.setAgent(agent);
            // should always result in either a non null object or an exception
            MessageEnvelope processEvn = processEnvelope(envelopeToProcess);
            retVal = new MessageProcessResult(processEvn, null);
            if (retVal.getProcessedMessage() != null)
                postProcessMessage(retVal);
        } catch (SmtpAgentException e) {
            // rethrow
            LOGGER.trace("Exiting processMessage(MimeMessage, NHINDAddressCollection, NHINDAddress", e);
            throw e;
        } catch (Exception e) {
            // audit the message rejection
            if (envelopeToProcess != null) {
                Collection<AuditContext> contexts = createContextCollectionFromMessage(envelopeToProcess, Arrays.asList(AuditEvents.DEFAULT_HEADER_CONTEXT));
                if (e instanceof NHINDException) {
                    NHINDException exception = (NHINDException) e;
                    if (exception.getError() != null) {
                        contexts.add(new DefaultAuditContext(AuditEvents.REJECTED_MESSAGE_REASON_CONTEXT, exception.getError().toString()));
                        if (exception.getError() != null && exception.getError() instanceof AgentException && ((AgentException) exception.getError()).getError() == AgentError.NoTrustedRecipients) {
                            StringBuilder rejectedRecips = new StringBuilder();
                            int cnt = 0;
                            for (NHINDAddress address : originalRecipList) {
                                rejectedRecips.append(address.getAddress());
                                if (++cnt < originalRecipList.size())
                                    rejectedRecips.append(", ");
                            }
                            contexts.add(new DefaultAuditContext(AuditEvents.REJECTED_RECIPIENTS_CONTEXT, rejectedRecips.toString()));
                        }
                    }
                }
                auditor.audit(PRINICPAL, new AuditEvent(AuditEvents.REJECTED_MESSAGE_NAME, AuditEvents.EVENT_TYPE), contexts);
            }
            LOGGER.trace("Exiting processMessage(MimeMessage, NHINDAddressCollection, NHINDAddress", e);
            throw new SmtpAgentException(SmtpAgentError.Unknown, e);
        }
        LOGGER.trace("Exiting processMessage(MimeMessage, NHINDAddressCollection, NHINDAddress");
        return retVal;
    } finally {
        GatewayState.getInstance().unlockFromProcessing();
    }
}
Also used : DefaultAuditContext(org.nhindirect.common.audit.DefaultAuditContext) NotificationMessage(org.nhindirect.stagent.mail.notifications.NotificationMessage) IncomingMessage(org.nhindirect.stagent.IncomingMessage) Message(org.nhindirect.stagent.mail.Message) MimeMessage(javax.mail.internet.MimeMessage) OutgoingMessage(org.nhindirect.stagent.OutgoingMessage) DefaultMessageEnvelope(org.nhindirect.stagent.DefaultMessageEnvelope) AgentException(org.nhindirect.stagent.AgentException) ArrayList(java.util.ArrayList) NHINDException(org.nhindirect.stagent.NHINDException) DefaultMessageEnvelope(org.nhindirect.stagent.DefaultMessageEnvelope) MessageEnvelope(org.nhindirect.stagent.MessageEnvelope) MessagingException(javax.mail.MessagingException) AgentException(org.nhindirect.stagent.AgentException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) NHINDException(org.nhindirect.stagent.NHINDException) NHINDAddress(org.nhindirect.stagent.NHINDAddress) NHINDAddressCollection(org.nhindirect.stagent.NHINDAddressCollection) Collection(java.util.Collection) AuditEvent(org.nhindirect.common.audit.AuditEvent)

Example 28 with MimeMessage

use of javax.mail.internet.MimeMessage in project nhin-d by DirectProject.

the class TrackIncomingNotification method service.

/**
	 * {@inheritDoc}
	 */
@Override
public void service(Mail mail) throws MessagingException {
    LOGGER.debug("Calling track incoming notification service");
    final MimeMessage msg = mail.getMessage();
    final NHINDAddressCollection recipients = getMailRecipients(mail);
    final NHINDAddress sender = getMailSender(mail);
    final Tx txToMonitor = getTxToTrack(msg, sender, recipients);
    // track message
    if (txToMonitor != null && (txToMonitor.getMsgType() == TxMessageType.DSN || txToMonitor.getMsgType() == TxMessageType.MDN)) {
        try {
            txService.trackMessage(txToMonitor);
        }///CLOVER:OFF
         catch (ServiceException ex) {
            LOGGER.warn("Failed to submit message to monitoring service.", ex);
        }
    ///CLOVER:ON
    }
    LOGGER.debug("Exiting track incoming notification service");
}
Also used : NHINDAddress(org.nhindirect.stagent.NHINDAddress) Tx(org.nhindirect.common.tx.model.Tx) ServiceException(org.nhindirect.common.rest.exceptions.ServiceException) MimeMessage(javax.mail.internet.MimeMessage) NHINDAddressCollection(org.nhindirect.stagent.NHINDAddressCollection)

Example 29 with MimeMessage

use of javax.mail.internet.MimeMessage in project nhin-d by DirectProject.

the class DefaultSmtpAgent method canonicalizeMessage.

/**
	 * Create a canonicalized version of a given mime message
	 * 
	 * @param mimeMessage
	 *            the message to canonicalize
	 * @return a mime message in the canonical form
	 * @throws IOException
	 * @throws MessagingException
	 */
protected MimeMessage canonicalizeMessage(MimeMessage mimeMessage) throws IOException, MessagingException {
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    CRLFOutputStream crlfOutputStream = new CRLFOutputStream(byteArrayOutputStream);
    mimeMessage.writeTo(crlfOutputStream);
    return new MimeMessage((Session) null, new ByteArrayInputStream(byteArrayOutputStream.toByteArray()));
}
Also used : MimeMessage(javax.mail.internet.MimeMessage) ByteArrayInputStream(java.io.ByteArrayInputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) CRLFOutputStream(com.sun.mail.util.CRLFOutputStream)

Example 30 with MimeMessage

use of javax.mail.internet.MimeMessage in project nhin-d by DirectProject.

the class NHINDSecurityAndTrustMailet_functionalTest method testProcessOutgoingMessageEndToEnd_multipleProcessThreads.

public void testProcessOutgoingMessageEndToEnd_multipleProcessThreads() throws Exception {
    new TestPlan() {

        protected String getMessageToProcess() throws Exception {
            return TestUtils.readMessageResource("PlainOutgoingMessage.txt");
        }

        final class MessageEncrypter implements Callable<MimeMessage> {

            private final Mailet theMailet;

            public MessageEncrypter(Mailet theMailet) {
                this.theMailet = theMailet;
            }

            public MimeMessage call() throws Exception {
                // encrypt
                String originalMessage = getMessageToProcess();
                MimeMessage msg = EntitySerializer.Default.deserialize(originalMessage);
                // add an MDN request
                msg.setHeader(MDNStandard.Headers.DispositionNotificationTo, msg.getHeader(MailStandard.Headers.From, ","));
                MockMail theMessage = new MockMail(msg);
                theMailet.service(theMessage);
                assertNotNull(theMessage);
                assertNotNull(theMessage.getMessage());
                msg = theMessage.getMessage();
                return msg;
            }
        }

        protected void performInner() throws Exception {
            ExecutorService execService = Executors.newFixedThreadPool(10);
            String originalMessage = getMessageToProcess();
            // execute 100 times
            GatewayState.getInstance().setSettingsUpdateInterval(1);
            Mailet theMailet = getMailet("ValidConfig.xml");
            List<Future<MimeMessage>> futures = new ArrayList<Future<MimeMessage>>();
            for (int i = 0; i < 100; ++i) {
                futures.add(execService.submit(new MessageEncrypter(theMailet)));
            }
            assertEquals(100, futures.size());
            GatewayState.getInstance().setSettingsUpdateInterval(300);
            for (Future<MimeMessage> future : futures) {
                // decrypt
                theMailet = getMailet("ValidConfigStateLine.txt");
                MockMail theMessage = new MockMail(future.get());
                theMailet.service(theMessage);
                assertNotNull(theMessage);
                assertNotNull(theMessage.getMessage());
                MimeMessage msg = theMessage.getMessage();
                assertFalse(SMIMEStandard.isEncrypted(msg));
                assertEquals(theMessage.getState(), Mail.TRANSPORT);
                Message compareMessage = new Message(theMessage.getMessage());
                // remove the MDN before comparison				
                compareMessage.removeHeader(MDNStandard.Headers.DispositionNotificationTo);
                assertEquals(originalMessage, compareMessage.toString());
            }
        }
    }.perform();
}
Also used : Message(org.nhindirect.stagent.mail.Message) MimeMessage(javax.mail.internet.MimeMessage) BaseTestPlan(org.nhindirect.gateway.testutils.BaseTestPlan) NHINDSecurityAndTrustMailet(org.nhindirect.gateway.smtp.james.mailet.NHINDSecurityAndTrustMailet) Mailet(org.apache.mailet.Mailet) Callable(java.util.concurrent.Callable) MimeMessage(javax.mail.internet.MimeMessage) ExecutorService(java.util.concurrent.ExecutorService) Future(java.util.concurrent.Future) ArrayList(java.util.ArrayList) List(java.util.List)

Aggregations

MimeMessage (javax.mail.internet.MimeMessage)1146 Test (org.junit.Test)374 InternetAddress (javax.mail.internet.InternetAddress)334 MessagingException (javax.mail.MessagingException)299 Session (javax.mail.Session)222 Properties (java.util.Properties)219 MimeMultipart (javax.mail.internet.MimeMultipart)208 MimeBodyPart (javax.mail.internet.MimeBodyPart)178 Date (java.util.Date)153 IOException (java.io.IOException)137 Message (javax.mail.Message)120 MimeMessageHelper (org.springframework.mail.javamail.MimeMessageHelper)107 SpringBootTest (org.springframework.boot.test.context.SpringBootTest)97 ZMimeMessage (com.zimbra.common.zmime.ZMimeMessage)83 InputStream (java.io.InputStream)82 ArrayList (java.util.ArrayList)81 Multipart (javax.mail.Multipart)75 DataHandler (javax.activation.DataHandler)73 ByteArrayOutputStream (java.io.ByteArrayOutputStream)72 BodyPart (javax.mail.BodyPart)70