Search in sources :

Example 1 with Message

use of javax.mail.Message in project Openfire by igniterealtime.

the class SendMail method sendMessage.

public boolean sendMessage(String message, String host, String port, String username, String password) {
    boolean ok = false;
    String uidString = "";
    try {
        // Set the email properties necessary to send email
        final Properties props = System.getProperties();
        props.put("mail.smtp.host", host);
        props.put("mail.transport.protocol", "smtp");
        props.put("mail.server", host);
        if (ModelUtil.hasLength(port)) {
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.port", port);
        }
        Session sess;
        if (ModelUtil.hasLength(password) && ModelUtil.hasLength(username)) {
            sess = Session.getInstance(props, new MailAuthentication(username, password));
        } else {
            sess = Session.getDefaultInstance(props, null);
        }
        Message msg = new MimeMessage(sess);
        StringTokenizer toST = new StringTokenizer(toField, ",");
        if (toST.countTokens() > 1) {
            InternetAddress[] address = new InternetAddress[toST.countTokens()];
            int addrIndex = 0;
            String addrString = "";
            while (toST.hasMoreTokens()) {
                addrString = toST.nextToken();
                address[addrIndex] = (new InternetAddress(addrString));
                addrIndex = addrIndex + 1;
            }
            msg.setRecipients(Message.RecipientType.TO, address);
        } else {
            InternetAddress[] address = { new InternetAddress(toField) };
            msg.setRecipients(Message.RecipientType.TO, address);
        }
        InternetAddress from = new InternetAddress(myAddress);
        msg.setFrom(from);
        msg.setSubject(subjectField);
        UID msgUID = new UID();
        uidString = msgUID.toString();
        msg.setHeader("X-Mailer", uidString);
        msg.setSentDate(new Date());
        MimeMultipart mp = new MimeMultipart();
        // create body part for textarea
        MimeBodyPart mbp1 = new MimeBodyPart();
        if (getCustomerName() != null) {
            messageText = "From: " + getCustomerName() + "\n" + messageText;
        }
        if (isHTML) {
            mbp1.setContent(messageText, "text/html");
        } else {
            mbp1.setContent(messageText, "text/plain");
        }
        mp.addBodyPart(mbp1);
        try {
            if (!isHTML) {
                msg.setContent(messageText, "text/plain");
            } else {
                msg.setContent(messageText, "text/html");
            }
            Transport.send(msg);
            ok = true;
        } catch (SendFailedException sfe) {
            Log.warn("Could not connect to SMTP server.");
        }
    } catch (Exception eq) {
        Log.warn("Could not connect to SMTP server.");
    }
    return ok;
}
Also used : InternetAddress(javax.mail.internet.InternetAddress) SendFailedException(javax.mail.SendFailedException) Message(javax.mail.Message) MimeMessage(javax.mail.internet.MimeMessage) Properties(java.util.Properties) Date(java.util.Date) SendFailedException(javax.mail.SendFailedException) UID(java.rmi.server.UID) StringTokenizer(java.util.StringTokenizer) MimeMessage(javax.mail.internet.MimeMessage) MimeMultipart(javax.mail.internet.MimeMultipart) MimeBodyPart(javax.mail.internet.MimeBodyPart) Session(javax.mail.Session)

Example 2 with Message

use of javax.mail.Message in project camel by apache.

the class MailConsumer method retrieveAllMessages.

private Message[] retrieveAllMessages() throws MessagingException {
    int total = folder.getMessageCount();
    List<Message> msgs = new ArrayList<Message>();
    // Note that message * numbers start at 1, not 0
    for (int i = 1; i <= total; i++) {
        try {
            Message msg = folder.getMessage(i);
            msgs.add(msg);
        } catch (Exception e) {
            if (skipFailedMessage) {
                LOG.debug("Skipping failed message at index " + i + " due " + e.getMessage(), e);
            } else if (handleFailedMessage) {
                handleException(e);
            } else {
                throw e;
            }
        }
    }
    return msgs.toArray(new Message[msgs.size()]);
}
Also used : Message(javax.mail.Message) ArrayList(java.util.ArrayList) MessagingException(javax.mail.MessagingException) FolderNotFoundException(javax.mail.FolderNotFoundException)

Example 3 with Message

use of javax.mail.Message in project camel by apache.

the class MailConsumer method createExchanges.

protected Queue<Exchange> createExchanges(List<KeyValueHolder<String, Message>> messages) throws MessagingException {
    Queue<Exchange> answer = new LinkedList<Exchange>();
    int fetchSize = getEndpoint().getConfiguration().getFetchSize();
    int count = fetchSize == -1 ? messages.size() : Math.min(fetchSize, messages.size());
    if (LOG.isDebugEnabled()) {
        LOG.debug("Fetching {} messages. Total {} messages.", count, messages.size());
    }
    for (int i = 0; i < count; i++) {
        try {
            KeyValueHolder<String, Message> holder = messages.get(i);
            String key = holder.getKey();
            Message message = holder.getValue();
            if (LOG.isTraceEnabled()) {
                LOG.trace("Mail #{} is of type: {} - {}", new Object[] { i, ObjectHelper.classCanonicalName(message), message });
            }
            if (!message.getFlags().contains(Flags.Flag.DELETED)) {
                Exchange exchange = getEndpoint().createExchange(message);
                if (getEndpoint().getConfiguration().isMapMailMessage()) {
                    // ensure the mail message is mapped, which can be ensured by touching the body/header/attachment
                    LOG.trace("Mapping #{} from javax.mail.Message to Camel MailMessage", i);
                    exchange.getIn().getBody();
                    exchange.getIn().getHeaders();
                    exchange.getIn().getAttachments();
                }
                // If the protocol is POP3 we need to remember the uid on the exchange
                // so we can find the mail message again later to be able to delete it
                // we also need to remember the UUID for idempotent repository
                exchange.setProperty(MAIL_MESSAGE_UID, key);
                answer.add(exchange);
            } else {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Skipping message as it was flagged as deleted: {}", MailUtils.dumpMessage(message));
                }
            }
        } catch (Exception e) {
            if (skipFailedMessage) {
                LOG.debug("Skipping failed message at index " + i + " due " + e.getMessage(), e);
            } else if (handleFailedMessage) {
                handleException(e);
            } else {
                throw e;
            }
        }
    }
    return answer;
}
Also used : Exchange(org.apache.camel.Exchange) Message(javax.mail.Message) LinkedList(java.util.LinkedList) MessagingException(javax.mail.MessagingException) FolderNotFoundException(javax.mail.FolderNotFoundException)

Example 4 with Message

use of javax.mail.Message in project camel by apache.

the class MailConsumer method processCommit.

/**
     * Strategy to flag the message after being processed.
     *
     * @param mail     the mail message
     * @param exchange the exchange
     */
protected void processCommit(Message mail, Exchange exchange) {
    try {
        // ensure folder is open
        if (!folder.isOpen()) {
            folder.open(Folder.READ_WRITE);
        }
        String uid = (String) exchange.removeProperty(MAIL_MESSAGE_UID);
        // Otherwise setting the DELETE/SEEN flag won't delete the message.
        if (getEndpoint().getConfiguration().getProtocol().startsWith("pop3")) {
            int count = folder.getMessageCount();
            Message found = null;
            LOG.trace("Looking for POP3Message with UID {} from folder with {} mails", uid, count);
            for (int i = 1; i <= count; ++i) {
                Message msg = folder.getMessage(i);
                if (uid.equals(getEndpoint().getMailUidGenerator().generateUuid(getEndpoint(), msg))) {
                    LOG.debug("Found POP3Message with UID {} from folder with {} mails", uid, count);
                    found = msg;
                    break;
                }
            }
            if (found == null) {
                boolean delete = getEndpoint().getConfiguration().isDelete();
                LOG.warn("POP3message not found in folder. Message cannot be marked as " + (delete ? "DELETED" : "SEEN"));
            } else {
                mail = found;
            }
        }
        org.apache.camel.Message in = exchange.getIn();
        MailConfiguration config = getEndpoint().getConfiguration();
        // header values override configuration values
        String copyTo = in.getHeader("copyTo", config.getCopyTo(), String.class);
        boolean delete = in.getHeader("delete", config.isDelete(), boolean.class);
        // Copy message into different imap folder if asked
        if (config.getProtocol().equals(MailUtils.PROTOCOL_IMAP) || config.getProtocol().equals(MailUtils.PROTOCOL_IMAPS)) {
            if (copyTo != null) {
                LOG.trace("IMAP message needs to be copied to {}", copyTo);
                Folder destFolder = store.getFolder(copyTo);
                if (!destFolder.exists()) {
                    destFolder.create(Folder.HOLDS_MESSAGES);
                }
                folder.copyMessages(new Message[] { mail }, destFolder);
                LOG.trace("IMAP message {} copied to {}", mail, copyTo);
            }
        }
        if (delete) {
            LOG.trace("Exchange processed, so flagging message as DELETED");
            mail.setFlag(Flags.Flag.DELETED, true);
        } else {
            LOG.trace("Exchange processed, so flagging message as SEEN");
            mail.setFlag(Flags.Flag.SEEN, true);
        }
        // need to confirm or remove on commit at last
        if (getEndpoint().getIdempotentRepository() != null) {
            if (getEndpoint().isIdempotentRepositoryRemoveOnCommit()) {
                getEndpoint().getIdempotentRepository().remove(uid);
            } else {
                getEndpoint().getIdempotentRepository().confirm(uid);
            }
        }
    } catch (MessagingException e) {
        getExceptionHandler().handleException("Error occurred during committing mail message: " + mail, exchange, e);
    }
}
Also used : Message(javax.mail.Message) MessagingException(javax.mail.MessagingException) Folder(javax.mail.Folder) IMAPFolder(com.sun.mail.imap.IMAPFolder)

Example 5 with Message

use of javax.mail.Message in project camel by apache.

the class MailConsumer method poll.

protected int poll() throws Exception {
    // must reset for each poll
    shutdownRunningTask = null;
    pendingExchanges = 0;
    int polledMessages = 0;
    ensureIsConnected();
    if (store == null || folder == null) {
        throw new IllegalStateException("MailConsumer did not connect properly to the MailStore: " + getEndpoint().getConfiguration().getMailStoreLogInformation());
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug("Polling mailbox folder: " + getEndpoint().getConfiguration().getMailStoreLogInformation());
    }
    if (getEndpoint().getConfiguration().getFetchSize() == 0) {
        LOG.warn("Fetch size is 0 meaning the configuration is set to poll no new messages at all. Camel will skip this poll.");
        return 0;
    }
    // ensure folder is open
    if (!folder.isOpen()) {
        folder.open(Folder.READ_WRITE);
    }
    try {
        int count = folder.getMessageCount();
        if (count > 0) {
            List<KeyValueHolder<String, Message>> messages = retrieveMessages();
            // we process the message and rollback due an exception
            if (getEndpoint().getConfiguration().isPeek()) {
                for (KeyValueHolder<String, Message> entry : messages) {
                    Message message = entry.getValue();
                    peekMessage(message);
                }
            }
            polledMessages = processBatch(CastUtils.cast(createExchanges(messages)));
            final MailBoxPostProcessAction postProcessor = getEndpoint().getPostProcessAction();
            if (postProcessor != null) {
                postProcessor.process(folder);
            }
        } else if (count == -1) {
            throw new MessagingException("Folder: " + folder.getFullName() + " is closed");
        }
    } catch (Exception e) {
        handleException(e);
    } finally {
        // need to ensure we release resources, but only if closeFolder or disconnect = true
        if (getEndpoint().getConfiguration().isCloseFolder() || getEndpoint().getConfiguration().isDisconnect()) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Close mailbox folder {} from {}", folder.getName(), getEndpoint().getConfiguration().getMailStoreLogInformation());
            }
            try {
                if (folder.isOpen()) {
                    folder.close(true);
                }
            } catch (Exception e) {
                // some mail servers will lock the folder so we ignore in this case (CAMEL-1263)
                LOG.debug("Could not close mailbox folder: " + folder.getName() + ". This exception is ignored.", e);
            }
        }
    }
    // should we disconnect, the header can override the configuration
    boolean disconnect = getEndpoint().getConfiguration().isDisconnect();
    if (disconnect) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Disconnecting from {}", getEndpoint().getConfiguration().getMailStoreLogInformation());
        }
        try {
            store.close();
        } catch (Exception e) {
            LOG.debug("Could not disconnect from {}: " + getEndpoint().getConfiguration().getMailStoreLogInformation() + ". This exception is ignored.", e);
        }
        store = null;
        folder = null;
    }
    return polledMessages;
}
Also used : Message(javax.mail.Message) MessagingException(javax.mail.MessagingException) KeyValueHolder(org.apache.camel.util.KeyValueHolder) MessagingException(javax.mail.MessagingException) FolderNotFoundException(javax.mail.FolderNotFoundException)

Aggregations

Message (javax.mail.Message)284 MimeMessage (javax.mail.internet.MimeMessage)166 MessagingException (javax.mail.MessagingException)101 InternetAddress (javax.mail.internet.InternetAddress)91 Test (org.junit.Test)82 Session (javax.mail.Session)78 Properties (java.util.Properties)73 Folder (javax.mail.Folder)72 MimeMultipart (javax.mail.internet.MimeMultipart)43 Date (java.util.Date)42 Store (javax.mail.Store)40 MimeBodyPart (javax.mail.internet.MimeBodyPart)34 IOException (java.io.IOException)29 Multipart (javax.mail.Multipart)27 Address (javax.mail.Address)23 ArrayList (java.util.ArrayList)22 Flags (javax.mail.Flags)22 MockEndpoint (org.apache.camel.component.mock.MockEndpoint)19 Mailbox (org.jvnet.mock_javamail.Mailbox)18 IMAPFolder (com.sun.mail.imap.IMAPFolder)17