Search in sources :

Example 36 with MimeMessage

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

the class IsNotificationTest method testIsNotification_DSNMessage_assertAllRecips.

@SuppressWarnings("unchecked")
public void testIsNotification_DSNMessage_assertAllRecips() throws Exception {
    MimeMessage msg = new MimeMessage(null, IOUtils.toInputStream(TestUtils.readMessageResource("DSNMessage.txt")));
    IsNotification matcher = new IsNotification();
    final Collection<MailAddress> initialRecips = new ArrayList<MailAddress>();
    for (InternetAddress addr : (InternetAddress[]) msg.getAllRecipients()) initialRecips.add(new MailAddress(addr.getAddress()));
    final MockMail mockMail = new MockMail(msg);
    mockMail.setRecipients(initialRecips);
    Collection<MailAddress> matchAddresses = matcher.match(mockMail);
    assertEquals(1, matchAddresses.size());
    assertEquals(initialRecips.iterator().next().toString(), matchAddresses.iterator().next().toString());
}
Also used : InternetAddress(javax.mail.internet.InternetAddress) MailAddress(org.apache.mailet.MailAddress) MimeMessage(javax.mail.internet.MimeMessage) MockMail(org.nhindirect.gateway.smtp.james.mailet.MockMail) ArrayList(java.util.ArrayList)

Example 37 with MimeMessage

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

the class IsNotificationTest method testIsNotification_plainMessage_assertNull.

@SuppressWarnings("unchecked")
public void testIsNotification_plainMessage_assertNull() throws Exception {
    MimeMessage msg = new MimeMessage(null, IOUtils.toInputStream(TestUtils.readMessageResource("PlainOutgoingMessage.txt")));
    IsNotification matcher = new IsNotification();
    final Collection<MailAddress> initialRecips = new ArrayList<MailAddress>();
    for (InternetAddress addr : (InternetAddress[]) msg.getAllRecipients()) initialRecips.add(new MailAddress(addr.getAddress()));
    final MockMail mockMail = new MockMail(msg);
    mockMail.setRecipients(initialRecips);
    Collection<MailAddress> matchAddresses = matcher.match(mockMail);
    assertEquals(null, matchAddresses);
}
Also used : InternetAddress(javax.mail.internet.InternetAddress) MailAddress(org.apache.mailet.MailAddress) MimeMessage(javax.mail.internet.MimeMessage) MockMail(org.nhindirect.gateway.smtp.james.mailet.MockMail) ArrayList(java.util.ArrayList)

Example 38 with MimeMessage

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

the class DirectXdMailet method service.

/*
     * (non-Javadoc)
     * 
     * @see org.apache.mailet.base.GenericMailet#service(org.apache.mailet.Mail)
     */
@Override
public void service(Mail mail) throws MessagingException {
    LOGGER.info("Servicing DirectXdMailet");
    if (StringUtils.isBlank(endpointUrl)) {
        LOGGER.error("DirectXdMailet endpoint URL cannot be empty or null.");
        throw new MessagingException("DirectXdMailet endpoint URL cannot be empty or null.");
    }
    boolean successfulTransaction = false;
    final MimeMessage msg = mail.getMessage();
    final boolean isReliableAndTimely = TxUtil.isReliableAndTimelyRequested(msg);
    final NHINDAddressCollection initialRecipients = getMailRecipients(mail);
    final NHINDAddressCollection xdRecipients = new NHINDAddressCollection();
    final NHINDAddress sender = getMailSender(mail);
    Tx txToTrack = null;
    // Get recipients and create a collection of Strings
    final List<String> recipAddresses = new ArrayList<String>();
    for (NHINDAddress addr : initialRecipients) {
        recipAddresses.add(addr.getAddress());
    }
    // Service XD* addresses
    if (getResolver().hasXdEndpoints(recipAddresses)) {
        LOGGER.info("Recipients include XD endpoints");
        try {
            //List<Address> xdAddresses = new ArrayList<Address>();
            for (String s : getResolver().getXdEndpoints(recipAddresses)) {
                //xdAddresses.add((new MailAddress(s)).toInternetAddress());
                xdRecipients.add(new NHINDAddress(s));
            }
            txToTrack = this.getTxToTrack(msg, sender, xdRecipients);
            // Replace recipients with only XD* addresses
            //msg.setRecipients(RecipientType.TO, xdAddresses.toArray(new Address[0]));
            msg.setRecipients(RecipientType.TO, xdRecipients.toArray(new Address[0]));
            // Transform MimeMessage into ProvideAndRegisterDocumentSetRequestType object
            ProvideAndRegisterDocumentSetRequestType request = getMimeXDSTransformer().transform(msg);
            for (String directTo : recipAddresses) {
                String response = getDocumentRepository().forwardRequest(endpointUrl, request, directTo, sender.toString());
                if (!isSuccessful(response)) {
                    LOGGER.error("DirectXdMailet failed to deliver XD message.");
                    LOGGER.error(response);
                } else {
                    successfulTransaction = true;
                    if (isReliableAndTimely && txToTrack != null && txToTrack.getMsgType() == TxMessageType.IMF) {
                        // send MDN dispatch for messages the recipients that were successful
                        final Collection<NotificationMessage> notifications = notificationProducer.produce(new Message(msg), xdRecipients.toInternetAddressCollection());
                        if (notifications != null && notifications.size() > 0) {
                            LOGGER.debug("Sending MDN \"dispathed\" messages");
                            // create a message for each notification and put it on James "stack"
                            for (NotificationMessage message : notifications) {
                                try {
                                    getMailetContext().sendMail(message);
                                } catch (Throwable t) {
                                    // don't kill the process if this fails
                                    LOGGER.error("Error sending MDN dispatched message.", t);
                                }
                            }
                        }
                    }
                }
            }
        } catch (Throwable e) {
            LOGGER.error("DirectXdMailet delivery failure", e);
        }
    }
    // this basically sets the message back to it's original state with SMTP addresses only
    if (getResolver().hasSmtpEndpoints(recipAddresses)) {
        LOGGER.info("Recipients include SMTP endpoints");
        mail.setRecipients(getSmtpRecips(recipAddresses));
    } else {
        LOGGER.info("Recipients do not include SMTP endpoints");
        // No SMTP addresses, ghost it
        mail.setState(Mail.GHOST);
    }
    if (!successfulTransaction) {
        if (txToTrack != null && txToTrack.getMsgType() == TxMessageType.IMF) {
            // for good measure, send DSN messages back to the original sender on failure
            // create a DSN message
            this.sendDSN(txToTrack, xdRecipients, false);
        }
    }
}
Also used : Tx(org.nhindirect.common.tx.model.Tx) Address(javax.mail.Address) MailAddress(org.apache.mailet.MailAddress) NHINDAddress(org.nhindirect.stagent.NHINDAddress) NotificationMessage(org.nhindirect.stagent.mail.notifications.NotificationMessage) Message(org.nhindirect.stagent.mail.Message) MimeMessage(javax.mail.internet.MimeMessage) MessagingException(javax.mail.MessagingException) NHINDAddressCollection(org.nhindirect.stagent.NHINDAddressCollection) ArrayList(java.util.ArrayList) NHINDAddress(org.nhindirect.stagent.NHINDAddress) NotificationMessage(org.nhindirect.stagent.mail.notifications.NotificationMessage) MimeMessage(javax.mail.internet.MimeMessage) ProvideAndRegisterDocumentSetRequestType(ihe.iti.xds_b._2007.ProvideAndRegisterDocumentSetRequestType)

Example 39 with MimeMessage

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

the class DSNGenerator method createDSNMessage.

/**
     * Creates a DSN message message.
     * @param originalSender The original sender of the message
     * @param originalSubject The subject of the original message
     * @param postmaster The postmaster address that the DSN message will be from
     * @param recipientDSNHeaders A list of recipient DSN headers to populate the delivery status part of the DSN message
     * @param messageDSNHeaders  The message DSN headers to populate the delivery status part of the DSN message
     * @param humanReadableText The human readable part (the first part) or the DSN message
     * @return A mime message containing the full DSN message
     * @throws MessagingException
     */
public MimeMessage createDSNMessage(InternetAddress originalSender, String originalSubject, InternetAddress postmaster, List<DSNRecipientHeaders> recipientDSNHeaders, DSNMessageHeaders messageDSNHeaders, MimeBodyPart humanReadableText) throws MessagingException {
    final DeliveryStatus deliveryStatus = createDeliveryStatus(recipientDSNHeaders, messageDSNHeaders);
    // assemble multipart report
    final MultipartReport multipartReport = new MultipartReport("", deliveryStatus);
    // set name of the delivery status file
    multipartReport.getBodyPart(DELIVERY_STATUS_MULTIPART_INDEX).setFileName("status.dat");
    // set text body part
    multipartReport.setTextBodyPart(humanReadableText);
    // create mime message to send from the MultipartReport
    final Properties properties = new Properties();
    properties.setProperty("mail.from", postmaster.getAddress());
    final Session session = Session.getInstance(properties);
    final MimeMessage destinationMessage = new MimeMessage(session);
    destinationMessage.setSentDate(Calendar.getInstance().getTime());
    destinationMessage.setContent(multipartReport);
    destinationMessage.setFrom(postmaster);
    destinationMessage.addRecipient(RecipientType.TO, originalSender);
    destinationMessage.setSubject(subjectPrefix + originalSubject);
    destinationMessage.setHeader(MailStandard.Headers.InReplyTo, messageDSNHeaders.getOriginalMessageId());
    destinationMessage.saveChanges();
    return destinationMessage;
}
Also used : MimeMessage(javax.mail.internet.MimeMessage) DeliveryStatus(com.sun.mail.dsn.DeliveryStatus) MultipartReport(com.sun.mail.dsn.MultipartReport) Properties(java.util.Properties) Session(javax.mail.Session)

Example 40 with MimeMessage

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

the class TxUtil_getMessageTypeTypeTest method testGetMessageType_IMFMessage.

@Test
public void testGetMessageType_IMFMessage() throws Exception {
    MimeMessage msg = TestUtils.readMimeMessageFromFile("MessageWithAttachment.txt");
    assertEquals(TxMessageType.IMF, TxUtil.getMessageType(msg));
}
Also used : MimeMessage(javax.mail.internet.MimeMessage) Test(org.junit.Test)

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