Search in sources :

Example 1 with EmailMessage

use of microsoft.exchange.webservices.data.core.service.item.EmailMessage in project nifi by apache.

the class ConsumeEWS method flushRemainingMessages.

/**
 * Will flush the remaining messages when this processor is stopped.
 */
protected void flushRemainingMessages(ProcessContext processContext) {
    Message emailMessage;
    try {
        while ((emailMessage = this.messageQueue.poll(1, TimeUnit.MILLISECONDS)) != null) {
            this.transfer(emailMessage, processContext, this.processSession);
            this.processSession.commit();
        }
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        this.logger.debug("Current thread is interrupted");
    }
}
Also used : Message(javax.mail.Message) EmailMessage(microsoft.exchange.webservices.data.core.service.item.EmailMessage) MimeMessage(javax.mail.internet.MimeMessage)

Example 2 with EmailMessage

use of microsoft.exchange.webservices.data.core.service.item.EmailMessage in project nifi by apache.

the class ConsumeEWS method fillMessageQueueIfNecessary.

/**
 * Fills the internal message queue if such queue is empty. This is due to
 * the fact that per single session there may be multiple messages retrieved
 * from the email server (see FETCH_SIZE).
 */
protected void fillMessageQueueIfNecessary(ProcessContext context) throws ProcessException {
    if (this.messageQueue.isEmpty()) {
        ExchangeService service = this.initializeIfNecessary(context);
        boolean deleteOnRead = context.getProperty(SHOULD_DELETE_MESSAGES).getValue().equals("true");
        boolean markAsRead = context.getProperty(SHOULD_MARK_READ).getValue().equals("true");
        String includeHeaders = context.getProperty(INCLUDE_EMAIL_HEADERS).getValue();
        String excludeHeaders = context.getProperty(EXCLUDE_EMAIL_HEADERS).getValue();
        List<String> includeHeadersList = null;
        List<String> excludeHeadersList = null;
        if (!StringUtils.isEmpty(includeHeaders)) {
            includeHeadersList = Arrays.asList(includeHeaders.split(","));
        }
        if (!StringUtils.isEmpty(excludeHeaders)) {
            excludeHeadersList = Arrays.asList(excludeHeaders.split(","));
        }
        try {
            // Get Folder
            Folder folder = getFolder(service);
            ItemView view = new ItemView(messageQueue.remainingCapacity());
            view.getOrderBy().add(ItemSchema.DateTimeReceived, SortDirection.Ascending);
            SearchFilter sf = new SearchFilter.SearchFilterCollection(LogicalOperator.And, new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false));
            FindItemsResults<Item> findResults = service.findItems(folder.getId(), sf, view);
            if (findResults == null || findResults.getItems().size() == 0) {
                return;
            }
            service.loadPropertiesForItems(findResults, PropertySet.FirstClassProperties);
            for (Item item : findResults) {
                EmailMessage ewsMessage = (EmailMessage) item;
                messageQueue.add(parseMessage(ewsMessage, includeHeadersList, excludeHeadersList));
                if (deleteOnRead) {
                    ewsMessage.delete(DeleteMode.HardDelete);
                } else if (markAsRead) {
                    ewsMessage.setIsRead(true);
                    ewsMessage.update(ConflictResolutionMode.AlwaysOverwrite);
                }
            }
            service.close();
        } catch (Exception e) {
            throw new ProcessException("Failed retrieving new messages from EWS.", e);
        }
    }
}
Also used : EmailMessage(microsoft.exchange.webservices.data.core.service.item.EmailMessage) SearchFilter(microsoft.exchange.webservices.data.search.filter.SearchFilter) Folder(microsoft.exchange.webservices.data.core.service.folder.Folder) URISyntaxException(java.net.URISyntaxException) MessagingException(javax.mail.MessagingException) EmailException(org.apache.commons.mail.EmailException) ProcessException(org.apache.nifi.processor.exception.ProcessException) IOException(java.io.IOException) ExchangeService(microsoft.exchange.webservices.data.core.ExchangeService) Item(microsoft.exchange.webservices.data.core.service.item.Item) ItemView(microsoft.exchange.webservices.data.search.ItemView) ProcessException(org.apache.nifi.processor.exception.ProcessException)

Example 3 with EmailMessage

use of microsoft.exchange.webservices.data.core.service.item.EmailMessage in project nifi by apache.

the class ConsumeEWS method onTrigger.

@Override
public void onTrigger(ProcessContext context, ProcessSession processSession) throws ProcessException {
    if (this.messageQueue == null) {
        int fetchSize = context.getProperty(FETCH_SIZE).evaluateAttributeExpressions().asInteger();
        this.messageQueue = new ArrayBlockingQueue<>(fetchSize);
    }
    this.folderName = context.getProperty(FOLDER).getValue();
    Message emailMessage = this.receiveMessage(context);
    if (emailMessage != null) {
        this.transfer(emailMessage, context, processSession);
    } else {
        // No new messages found, yield the processor
        context.yield();
    }
}
Also used : Message(javax.mail.Message) EmailMessage(microsoft.exchange.webservices.data.core.service.item.EmailMessage) MimeMessage(javax.mail.internet.MimeMessage)

Example 4 with EmailMessage

use of microsoft.exchange.webservices.data.core.service.item.EmailMessage in project nifi by apache.

the class ConsumeEWS method receiveMessage.

/**
 * Receives message from the internal queue filling up the queue if
 * necessary.
 */
protected Message receiveMessage(ProcessContext context) {
    Message emailMessage = null;
    try {
        this.fillMessageQueueIfNecessary(context);
        emailMessage = this.messageQueue.poll(1, TimeUnit.MILLISECONDS);
    } catch (InterruptedException e) {
        context.yield();
        this.logger.error("Failed retrieving messages from EWS.", e);
        Thread.currentThread().interrupt();
        this.logger.debug("Current thread is interrupted");
    }
    return emailMessage;
}
Also used : Message(javax.mail.Message) EmailMessage(microsoft.exchange.webservices.data.core.service.item.EmailMessage) MimeMessage(javax.mail.internet.MimeMessage)

Example 5 with EmailMessage

use of microsoft.exchange.webservices.data.core.service.item.EmailMessage in project nifi by apache.

the class ConsumeEWS method parseMessage.

public MimeMessage parseMessage(EmailMessage item, List<String> hdrIncludeList, List<String> hdrExcludeList) throws Exception {
    EmailMessage ewsMessage = item;
    final String bodyText = ewsMessage.getBody().toString();
    MultiPartEmail mm;
    if (ewsMessage.getBody().getBodyType() == BodyType.HTML) {
        mm = new HtmlEmail().setHtmlMsg(bodyText);
    } else {
        mm = new MultiPartEmail();
        mm.setMsg(bodyText);
    }
    mm.setHostName("NiFi-EWS");
    // from
    mm.setFrom(ewsMessage.getFrom().getAddress());
    // to recipients
    ewsMessage.getToRecipients().forEach(x -> {
        try {
            mm.addTo(x.getAddress());
        } catch (EmailException e) {
            throw new ProcessException("Failed to add TO recipient.", e);
        }
    });
    // cc recipients
    ewsMessage.getCcRecipients().forEach(x -> {
        try {
            mm.addCc(x.getAddress());
        } catch (EmailException e) {
            throw new ProcessException("Failed to add CC recipient.", e);
        }
    });
    // subject
    mm.setSubject(ewsMessage.getSubject());
    // sent date
    mm.setSentDate(ewsMessage.getDateTimeSent());
    // add message headers
    ewsMessage.getInternetMessageHeaders().getItems().stream().filter(x -> (hdrIncludeList == null || hdrIncludeList.isEmpty() || hdrIncludeList.contains(x.getName())) && (hdrExcludeList == null || hdrExcludeList.isEmpty() || !hdrExcludeList.contains(x.getName()))).forEach(x -> mm.addHeader(x.getName(), x.getValue()));
    // Any attachments
    if (ewsMessage.getHasAttachments()) {
        ewsMessage.getAttachments().forEach(x -> {
            try {
                FileAttachment file = (FileAttachment) x;
                file.load();
                ByteArrayDataSource bds = new ByteArrayDataSource(file.getContent(), file.getContentType());
                mm.attach(bds, file.getName(), "", EmailAttachment.ATTACHMENT);
            } catch (MessagingException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }
    mm.buildMimeMessage();
    return mm.getMimeMessage();
}
Also used : OutputStreamCallback(org.apache.nifi.processor.io.OutputStreamCallback) StandardValidators(org.apache.nifi.processor.util.StandardValidators) Message(javax.mail.Message) ByteArrayDataSource(javax.mail.util.ByteArrayDataSource) Arrays(java.util.Arrays) URISyntaxException(java.net.URISyntaxException) FindItemsResults(microsoft.exchange.webservices.data.search.FindItemsResults) LoggerFactory(org.slf4j.LoggerFactory) FolderTraversal(microsoft.exchange.webservices.data.core.enumeration.search.FolderTraversal) MessagingException(javax.mail.MessagingException) StringUtils(org.apache.commons.lang3.StringUtils) PropertyDescriptor(org.apache.nifi.components.PropertyDescriptor) EmailMessageSchema(microsoft.exchange.webservices.data.core.service.schema.EmailMessageSchema) FolderSchema(microsoft.exchange.webservices.data.core.service.schema.FolderSchema) PropertySet(microsoft.exchange.webservices.data.core.PropertySet) IAutodiscoverRedirectionUrl(microsoft.exchange.webservices.data.autodiscover.IAutodiscoverRedirectionUrl) URI(java.net.URI) BodyType(microsoft.exchange.webservices.data.core.enumeration.property.BodyType) FlowFile(org.apache.nifi.flowfile.FlowFile) ExchangeService(microsoft.exchange.webservices.data.core.ExchangeService) DeleteMode(microsoft.exchange.webservices.data.core.enumeration.service.DeleteMode) ExchangeVersion(microsoft.exchange.webservices.data.core.enumeration.misc.ExchangeVersion) Set(java.util.Set) BlockingQueue(java.util.concurrent.BlockingQueue) FolderView(microsoft.exchange.webservices.data.search.FolderView) ItemSchema(microsoft.exchange.webservices.data.core.service.schema.ItemSchema) ArrayBlockingQueue(java.util.concurrent.ArrayBlockingQueue) SortDirection(microsoft.exchange.webservices.data.core.enumeration.search.SortDirection) InputRequirement(org.apache.nifi.annotation.behavior.InputRequirement) List(java.util.List) ConflictResolutionMode(microsoft.exchange.webservices.data.core.enumeration.service.ConflictResolutionMode) EmailException(org.apache.commons.mail.EmailException) Tags(org.apache.nifi.annotation.documentation.Tags) FileAttachment(microsoft.exchange.webservices.data.property.complex.FileAttachment) ExchangeCredentials(microsoft.exchange.webservices.data.credential.ExchangeCredentials) Address(javax.mail.Address) SearchFilter(microsoft.exchange.webservices.data.search.filter.SearchFilter) CapabilityDescription(org.apache.nifi.annotation.documentation.CapabilityDescription) EmailMessage(microsoft.exchange.webservices.data.core.service.item.EmailMessage) HtmlEmail(org.apache.commons.mail.HtmlEmail) Flags(javax.mail.Flags) ProcessException(org.apache.nifi.processor.exception.ProcessException) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) EmailAttachment(org.apache.commons.mail.EmailAttachment) Relationship(org.apache.nifi.processor.Relationship) LogicalOperator(microsoft.exchange.webservices.data.core.enumeration.search.LogicalOperator) OutputStream(java.io.OutputStream) WellKnownFolderName(microsoft.exchange.webservices.data.core.enumeration.property.WellKnownFolderName) Logger(org.slf4j.Logger) Validator(org.apache.nifi.components.Validator) ItemView(microsoft.exchange.webservices.data.search.ItemView) ProcessContext(org.apache.nifi.processor.ProcessContext) ProcessSession(org.apache.nifi.processor.ProcessSession) IOException(java.io.IOException) MultiPartEmail(org.apache.commons.mail.MultiPartEmail) MimeMessage(javax.mail.internet.MimeMessage) TimeUnit(java.util.concurrent.TimeUnit) Item(microsoft.exchange.webservices.data.core.service.item.Item) WebCredentials(microsoft.exchange.webservices.data.credential.WebCredentials) FindFoldersResults(microsoft.exchange.webservices.data.search.FindFoldersResults) AbstractProcessor(org.apache.nifi.processor.AbstractProcessor) Folder(microsoft.exchange.webservices.data.core.service.folder.Folder) OnStopped(org.apache.nifi.annotation.lifecycle.OnStopped) EmailMessage(microsoft.exchange.webservices.data.core.service.item.EmailMessage) ProcessException(org.apache.nifi.processor.exception.ProcessException) MessagingException(javax.mail.MessagingException) MultiPartEmail(org.apache.commons.mail.MultiPartEmail) FileAttachment(microsoft.exchange.webservices.data.property.complex.FileAttachment) HtmlEmail(org.apache.commons.mail.HtmlEmail) EmailException(org.apache.commons.mail.EmailException) ByteArrayDataSource(javax.mail.util.ByteArrayDataSource) URISyntaxException(java.net.URISyntaxException) MessagingException(javax.mail.MessagingException) EmailException(org.apache.commons.mail.EmailException) ProcessException(org.apache.nifi.processor.exception.ProcessException) IOException(java.io.IOException)

Aggregations

EmailMessage (microsoft.exchange.webservices.data.core.service.item.EmailMessage)7 Message (javax.mail.Message)4 MimeMessage (javax.mail.internet.MimeMessage)4 Item (microsoft.exchange.webservices.data.core.service.item.Item)4 IOException (java.io.IOException)2 URISyntaxException (java.net.URISyntaxException)2 MessagingException (javax.mail.MessagingException)2 ExchangeService (microsoft.exchange.webservices.data.core.ExchangeService)2 PropertySet (microsoft.exchange.webservices.data.core.PropertySet)2 ServiceLocalException (microsoft.exchange.webservices.data.core.exception.service.local.ServiceLocalException)2 Folder (microsoft.exchange.webservices.data.core.service.folder.Folder)2 ConfigurationException (nl.nn.adapterframework.configuration.ConfigurationException)2 ListenerException (nl.nn.adapterframework.core.ListenerException)2 XmlBuilder (nl.nn.adapterframework.util.XmlBuilder)2 ByteArrayInputStream (java.io.ByteArrayInputStream)1 OutputStream (java.io.OutputStream)1 URI (java.net.URI)1 SimpleDateFormat (java.text.SimpleDateFormat)1 ArrayList (java.util.ArrayList)1 Arrays (java.util.Arrays)1