Example usage for javax.mail MessagingException getMessage

List of usage examples for javax.mail MessagingException getMessage

Introduction

In this page you can find the example usage for javax.mail MessagingException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:com.cws.esolutions.core.utils.EmailUtils.java

/**
 * Processes and sends an email message as generated by the requesting
 * application. This method is utilized with a JNDI datasource.
 *
 * @param dataSource - The email message
 * @param authRequired - <code>true</code> if authentication is required, <code>false</code> otherwise
 * @param authList - If authRequired is true, this must be populated with the auth info
 * @return List - The list of email messages in the mailstore
 * @throws MessagingException {@link javax.mail.MessagingException} if an exception occurs during processing
 *///from   w w w .j a  va  2 s . c  om
public static final synchronized List<EmailMessage> readEmailMessages(final Properties dataSource,
        final boolean authRequired, final List<String> authList) throws MessagingException {
    final String methodName = EmailUtils.CNAME
            + "#readEmailMessages(final Properties dataSource, final boolean authRequired, final List<String> authList) throws MessagingException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("dataSource: {}", dataSource);
        DEBUGGER.debug("authRequired: {}", authRequired);
        DEBUGGER.debug("authList: {}", authList);
    }

    Folder mailFolder = null;
    Session mailSession = null;
    Folder archiveFolder = null;
    List<EmailMessage> emailMessages = null;

    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.HOUR, -24);

    final Long TIME_PERIOD = cal.getTimeInMillis();
    final URLName URL_NAME = (authRequired)
            ? new URLName(dataSource.getProperty("mailtype"), dataSource.getProperty("host"),
                    Integer.parseInt(dataSource.getProperty("port")), null, authList.get(0), authList.get(1))
            : new URLName(dataSource.getProperty("mailtype"), dataSource.getProperty("host"),
                    Integer.parseInt(dataSource.getProperty("port")), null, null, null);

    if (DEBUG) {
        DEBUGGER.debug("timePeriod: {}", TIME_PERIOD);
        DEBUGGER.debug("URL_NAME: {}", URL_NAME);
    }

    try {
        // Set up mail session
        mailSession = (authRequired) ? Session.getDefaultInstance(dataSource, new SMTPAuthenticator())
                : Session.getDefaultInstance(dataSource);

        if (DEBUG) {
            DEBUGGER.debug("mailSession: {}", mailSession);
        }

        if (mailSession == null) {
            throw new MessagingException("Unable to configure email services");
        }

        mailSession.setDebug(DEBUG);
        Store mailStore = mailSession.getStore(URL_NAME);
        mailStore.connect();

        if (DEBUG) {
            DEBUGGER.debug("mailStore: {}", mailStore);
        }

        if (!(mailStore.isConnected())) {
            throw new MessagingException("Failed to connect to mail service. Cannot continue.");
        }

        mailFolder = mailStore.getFolder("inbox");
        archiveFolder = mailStore.getFolder("archive");

        if (!(mailFolder.exists())) {
            throw new MessagingException("Requested folder does not exist. Cannot continue.");
        }

        mailFolder.open(Folder.READ_WRITE);

        if ((!(mailFolder.isOpen())) || (!(mailFolder.hasNewMessages()))) {
            throw new MessagingException("Failed to open requested folder. Cannot continue");
        }

        if (!(archiveFolder.exists())) {
            archiveFolder.create(Folder.HOLDS_MESSAGES);
        }

        Message[] mailMessages = mailFolder.getMessages();

        if (mailMessages.length == 0) {
            throw new MessagingException("No messages were found in the provided store.");
        }

        emailMessages = new ArrayList<EmailMessage>();

        for (Message message : mailMessages) {
            if (DEBUG) {
                DEBUGGER.debug("MailMessage: {}", message);
            }

            // validate the message here
            String messageId = message.getHeader("Message-ID")[0];
            Long messageDate = message.getReceivedDate().getTime();

            if (DEBUG) {
                DEBUGGER.debug("messageId: {}", messageId);
                DEBUGGER.debug("messageDate: {}", messageDate);
            }

            // only get emails for the last 24 hours
            // this should prevent us from pulling too
            // many emails
            if (messageDate >= TIME_PERIOD) {
                // process it
                Multipart attachment = (Multipart) message.getContent();
                Map<String, InputStream> attachmentList = new HashMap<String, InputStream>();

                for (int x = 0; x < attachment.getCount(); x++) {
                    BodyPart bodyPart = attachment.getBodyPart(x);

                    if (!(Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition()))) {
                        continue;
                    }

                    attachmentList.put(bodyPart.getFileName(), bodyPart.getInputStream());
                }

                List<String> toList = new ArrayList<String>();
                List<String> ccList = new ArrayList<String>();
                List<String> bccList = new ArrayList<String>();
                List<String> fromList = new ArrayList<String>();

                for (Address from : message.getFrom()) {
                    fromList.add(from.toString());
                }

                if ((message.getRecipients(RecipientType.TO) != null)
                        && (message.getRecipients(RecipientType.TO).length != 0)) {
                    for (Address to : message.getRecipients(RecipientType.TO)) {
                        toList.add(to.toString());
                    }
                }

                if ((message.getRecipients(RecipientType.CC) != null)
                        && (message.getRecipients(RecipientType.CC).length != 0)) {
                    for (Address cc : message.getRecipients(RecipientType.CC)) {
                        ccList.add(cc.toString());
                    }
                }

                if ((message.getRecipients(RecipientType.BCC) != null)
                        && (message.getRecipients(RecipientType.BCC).length != 0)) {
                    for (Address bcc : message.getRecipients(RecipientType.BCC)) {
                        bccList.add(bcc.toString());
                    }
                }

                EmailMessage emailMessage = new EmailMessage();
                emailMessage.setMessageTo(toList);
                emailMessage.setMessageCC(ccList);
                emailMessage.setMessageBCC(bccList);
                emailMessage.setEmailAddr(fromList);
                emailMessage.setMessageAttachments(attachmentList);
                emailMessage.setMessageDate(message.getSentDate());
                emailMessage.setMessageSubject(message.getSubject());
                emailMessage.setMessageBody(message.getContent().toString());
                emailMessage.setMessageSources(message.getHeader("Received"));

                if (DEBUG) {
                    DEBUGGER.debug("emailMessage: {}", emailMessage);
                }

                emailMessages.add(emailMessage);

                if (DEBUG) {
                    DEBUGGER.debug("emailMessages: {}", emailMessages);
                }
            }

            // archive it
            archiveFolder.open(Folder.READ_WRITE);

            if (archiveFolder.isOpen()) {
                mailFolder.copyMessages(new Message[] { message }, archiveFolder);
                message.setFlag(Flags.Flag.DELETED, true);
            }
        }
    } catch (IOException iox) {
        throw new MessagingException(iox.getMessage(), iox);
    } catch (MessagingException mex) {
        throw new MessagingException(mex.getMessage(), mex);
    } finally {
        try {
            if ((mailFolder != null) && (mailFolder.isOpen())) {
                mailFolder.close(true);
            }

            if ((archiveFolder != null) && (archiveFolder.isOpen())) {
                archiveFolder.close(false);
            }
        } catch (MessagingException mx) {
            ERROR_RECORDER.error(mx.getMessage(), mx);
        }
    }

    return emailMessages;
}

From source file:com.cubusmail.mail.util.MessageUtils.java

/**
 * Filter the messages./* ww w . j a va 2s  .  c  o m*/
 * 
 * @param msgs
 * @param searchFields
 * @param searchText
 * @return
 */
public static Message[] quickFilterMessages(Message[] msgs, String searchFields, String searchText) {

    if (!StringUtils.isEmpty(searchFields) && !StringUtils.isEmpty(searchText)) {
        searchFields = StringUtils.remove(searchFields, '[');
        searchFields = StringUtils.remove(searchFields, ']');
        searchFields = StringUtils.remove(searchFields, '\"');
        String[] fields = StringUtils.split(searchFields, ',');
        List<Message> filteredMsgs = new ArrayList<Message>();

        Date searchDate = null;
        try {
            searchDate = DateUtils.parseDate(searchText, new String[] { "dd.MM.yyyy" });
        } catch (Exception e) {
            // do nothing
        }

        try {
            for (Message message : msgs) {
                boolean contains = false;
                for (String searchField : fields) {
                    if (MessageListFields.SUBJECT.name().equals(searchField)) {
                        String subject = message.getSubject();
                        contains = StringUtils.containsIgnoreCase(subject, searchText);
                    } else if (MessageListFields.FROM.name().equals(searchField)) {
                        String from = MessageUtils.getMailAdressString(message.getFrom(),
                                AddressStringType.COMPLETE);
                        contains = StringUtils.containsIgnoreCase(from, searchText) || contains;
                    } else if (searchDate != null && MessageListFields.DATE.name().equals(searchField)) {
                        Date sendDate = message.getSentDate();
                        contains = (sendDate != null && DateUtils.isSameDay(searchDate, sendDate)) || contains;
                    }
                }
                if (contains) {
                    filteredMsgs.add(message);
                }
            }
        } catch (MessagingException ex) {
            log.warn(ex.getMessage(), ex);
        }

        return filteredMsgs.toArray(new Message[0]);
    }

    return msgs;
}

From source file:com.cubusmail.mail.util.MessageUtils.java

/**
 * @param mailFolder//from   www.j  a  v  a  2  s. c  om
 * @param msgs
 * @param extendedSearchFields
 * @param params
 * @return
 */
public static Message[] filterMessages(IMailFolder mailFolder, Message[] msgs, String extendedSearchFields,
        String[][] params) {

    if (!StringUtils.isEmpty(extendedSearchFields)) {
        String[] fields = StringUtils.split(extendedSearchFields, ',');

        List<Message> filteredMsgs = new ArrayList<Message>();
        String fromValue = getParamValue(params, SearchFields.FROM.name());
        String toValue = getParamValue(params, SearchFields.TO.name());
        String ccValue = getParamValue(params, SearchFields.CC.name());
        String subjectValue = getParamValue(params, SearchFields.SUBJECT.name());
        String contentValue = getParamValue(params, SearchFields.CONTENT.name());
        String dateFromValue = getParamValue(params, SearchFields.DATE_FROM.name());
        String dateToValue = getParamValue(params, SearchFields.DATE_TO.name());

        try {
            // Body search
            if (StringUtils.contains(extendedSearchFields, SearchFields.CONTENT.name())) {
                BodyTerm term = new BodyTerm(contentValue);
                msgs = mailFolder.search(term, msgs);
                if (msgs == null) {
                    msgs = new Message[0];
                }
            }

            for (Message message : msgs) {
                boolean contains = true;
                for (String searchField : fields) {
                    if (SearchFields.FROM.name().equals(searchField)) {
                        String from = MessageUtils.getMailAdressString(message.getFrom(),
                                AddressStringType.COMPLETE);
                        contains = StringUtils.containsIgnoreCase(from, fromValue);
                    }
                    if (contains && SearchFields.TO.name().equals(searchField)) {
                        String to = MessageUtils.getMailAdressString(
                                message.getRecipients(Message.RecipientType.TO), AddressStringType.COMPLETE);
                        if (!StringUtils.isEmpty(to)) {
                            contains = StringUtils.containsIgnoreCase(to, toValue);
                        } else {
                            contains = false;
                        }
                    }
                    if (contains && SearchFields.CC.name().equals(searchField)) {
                        String cc = MessageUtils.getMailAdressString(
                                message.getRecipients(Message.RecipientType.CC), AddressStringType.COMPLETE);
                        if (!StringUtils.isEmpty(cc)) {
                            contains = StringUtils.containsIgnoreCase(cc, ccValue);
                        } else {
                            contains = false;
                        }
                    }
                    if (contains && SearchFields.SUBJECT.name().equals(searchField)) {
                        if (!StringUtils.isEmpty(message.getSubject())) {
                            contains = StringUtils.containsIgnoreCase(message.getSubject(), subjectValue);
                        } else {
                            contains = false;
                        }
                    }
                    if (contains && SearchFields.DATE_FROM.name().equals(searchField)) {
                        Date dateFrom = new Date(Long.parseLong(dateFromValue));
                        if (message.getSentDate() != null) {
                            contains = !message.getSentDate().before(dateFrom);
                        } else {
                            contains = false;
                        }
                    }
                    if (contains && SearchFields.DATE_TO.name().equals(searchField)) {
                        Date dateTo = new Date(Long.parseLong(dateToValue));
                        if (message.getSentDate() != null) {
                            contains = !message.getSentDate().after(dateTo);
                        } else {
                            contains = false;
                        }
                    }
                }
                if (contains) {
                    filteredMsgs.add(message);
                }
            }
        } catch (MessagingException ex) {
            log.warn(ex.getMessage());
        }

        return filteredMsgs.toArray(new Message[0]);
    }

    return msgs;
}

From source file:br.com.valecard.listeners.SendMailListener.java

@Override
public void onApplicationEvent(SendMailEvent event) {
    MimeMessage mm = mailSender.createMimeMessage();
    final String property = event.getProperty();
    try {/*from  www  .  j  av a  2s. c  o  m*/
        mm.setRecipients(Message.RecipientType.TO, property);
        mm.setText(property);
        //            mm.addHeader(XMC_TRACK, track);
        //            mm.addHeader(XMC_TEMPLATE, property);
        //            mm.addHeader(XMC_MERGE_VARS, mergeVars);
    } catch (MessagingException ex) {
        LOG.log(Level.WARNING, ex.getMessage(), ex);
    }
    try {
        mailSender.send(mm);
    } catch (MailException ex) {
        LOG.log(Level.WARNING, ex.getMessage(), ex);
    }
}

From source file:org.apache.james.smtpserver.SetMimeHeaderHandler.java

/**
 * Adds header to the message//from w w  w. ja v a2  s. c  om
 * 
 * @see org.apache.james.smtpserver.JamesMessageHook#onMessage(org.apache.james.protocols.smtp.SMTPSession,
 *      org.apache.mailet.Mail)
 */
public HookResult onMessage(SMTPSession session, Mail mail) {
    try {
        MimeMessage message = mail.getMessage();

        // Set the header name and value (supplied at init time).
        if (headerName != null) {
            message.setHeader(headerName, headerValue);
            message.saveChanges();
        }

    } catch (javax.mail.MessagingException me) {
        session.getLogger().error(me.getMessage());
    }

    return new HookResult(HookReturnCode.DECLINED);
}

From source file:com.cubusmail.server.mail.util.MessageComparator.java

public int compare(Message msg1, Message msg2) {

    int result = 0;

    if (msg1.isExpunged() || msg2.isExpunged()) {
        return result;
    }/*from  w w w . ja v a2 s  .co  m*/

    try {
        if (MessageListFields.SUBJECT == this.field) {
            if (msg1.getSubject() != null && msg2.getSubject() != null) {
                result = msg1.getSubject().compareToIgnoreCase(msg2.getSubject());
            } else {
                result = -1;
            }
        } else if (MessageListFields.FROM == this.field) {
            String fromString1 = MessageUtils.getMailAdressString(msg1.getFrom(), AddressStringType.PERSONAL);
            String fromString2 = MessageUtils.getMailAdressString(msg2.getFrom(), AddressStringType.PERSONAL);
            if (fromString1 != null && fromString2 != null) {
                result = fromString1.compareToIgnoreCase(fromString2);
            } else {
                result = -1;
            }
        } else if (MessageListFields.SEND_DATE == this.field) {
            Date date1 = msg1.getSentDate();
            Date date2 = msg2.getSentDate();
            if (date1 != null && date2 != null) {
                result = date1.compareTo(date2);
            } else {
                result = -1;
            }
        } else if (MessageListFields.SIZE == this.field) {
            int size1 = msg1.getSize();
            int size2 = msg2.getSize();
            result = Integer.valueOf(size1).compareTo(Integer.valueOf(size2));

        }
    } catch (MessagingException e) {
        log.warn(e.getMessage(), e);
    }

    if (!this.ascending) {
        result = result * (-1);
    }

    return result;
}

From source file:org.nuxeo.ecm.automation.client.jaxrs.impl.MultipartRequestEntity.java

public void writeTo(OutputStream arg0) throws IOException {
    try {//from   www.  j  a  v a2s . c o m
        mp.writeTo(arg0);
    } catch (MessagingException e) {
        IOException ioe = new IOException(e.getMessage());
        ioe.initCause(e);
        throw ioe;
    }
}

From source file:com.thinkbiganalytics.metadata.sla.SlaEmailService.java

/**
 * Send an email// w  w w.j  a v  a  2  s .co m
 *
 * @param to      the user(s) to send the email to
 * @param subject the subject of the email
 * @param body    the email body
 */
public void sendMail(String to, String subject, String body) {

    try {
        if (testConnection()) {
            MimeMessage message = mailSender.createMimeMessage();
            String fromAddress = StringUtils.defaultIfBlank(emailConfiguration.getFrom(),
                    emailConfiguration.getUsername());
            message.setFrom(new InternetAddress(fromAddress));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
            message.setSubject(subject);
            message.setText(body);
            mailSender.send(message);
            log.debug("Email send to {}", to);
        }
    } catch (MessagingException ex) {
        log.error("Exception while sending mail : {}", ex.getMessage());
        Throwables.propagate(ex);

    }
}

From source file:org.nuxeo.cm.event.MailInjectionListener.java

public void handleEvent(Event event) throws ClientException {
    MailService mailService = Framework.getService(MailService.class);
    MessageActionPipe pipe = mailService.getPipe(MAILBOX_PIPE);

    Visitor visitor = new Visitor(pipe);
    Thread.currentThread().setContextClassLoader(Framework.class.getClassLoader());

    Folder rootFolder = null;//  www  . j  a  va 2  s  .  c  om

    try (CoreSession session = CoreInstance.openCoreSessionSystem(null)) {
        // initialize context
        ExecutionContext initialExecutionContext = new ExecutionContext();
        initialExecutionContext.put(AbstractCaseManagementMailAction.CORE_SESSION_KEY, session);
        initialExecutionContext.put(AbstractCaseManagementMailAction.MIMETYPE_SERVICE_KEY,
                Framework.getService(MimetypeRegistry.class));
        initialExecutionContext.put(AbstractCaseManagementMailAction.CASEMANAGEMENT_SERVICE_KEY,
                Framework.getService(CaseDistributionService.class));

        // open store
        Store store = mailService.getConnectedStore(IMPORT_MAILBOX);
        rootFolder = store.getFolder(INBOX);
        rootFolder.open(Folder.READ_WRITE);
        Flags flags = new Flags();
        flags.add(Flag.SEEN);
        SearchTerm term = new FlagTerm(flags, false);
        Message[] unreadMessages = rootFolder.search(term);

        // perform import
        visitor.visit(unreadMessages, initialExecutionContext);

        // save session
        session.save();

        if (rootFolder.isOpen()) {
            try {
                rootFolder.close(true);
            } catch (MessagingException e) {
                log.error(e.getMessage(), e);
            }
        }
    } catch (MessagingException e) {
        log.error(e, e);
    }
}

From source file:Utility.MyFTPClient.java

public boolean sendFile(File theFile) {
    errorFree = true;// w w  w . j av  a2 s .  co  m
    try {
        client.connect("ftp.listrakbi.com", 21);

        if (client.login(AKC_Creds.LISTRAK_FTP_LOGIN, AKC_Creds.LISTRAK_FTP_PWD)) {
            System.out.println("FTP login Success");
        } else {
            System.out.println("FTP login Failed");
            try {
                Emailer.Send(AKC_Creds.ANH_EMAIL, AKC_Creds.ANH_EMAIL_PWD, AKC_Creds.ANH_EMAIL,
                        "Auto notification from server : ERROR", "\n\n Connection to Listrak FTP failed.");
            } catch (MessagingException ex) {
                System.out.println(ex.getMessage());
            }
            errorFree = false;
        }

        //
        // Create an InputStream of the file to be uploaded
        //
        fis = new FileInputStream(theFile);
        String remoteFileName = theFile.getAbsolutePath()
                .substring(theFile.getAbsolutePath().lastIndexOf("\\") + 1);
        //
        // Store file to server
        //
        if (client.storeFile(remoteFileName, fis)) {
            System.out.println("FTP storeFile " + remoteFileName + " Success");
        } else {
            System.out.println("FTP storeFile Failed");
            errorFree = false;
            try {
                Emailer.Send(AKC_Creds.ANH_EMAIL, AKC_Creds.ANH_EMAIL_PWD, AKC_Creds.ANH_EMAIL,
                        "Auto notification from server : ERROR",
                        "\n\n The system was able to connect with Listrak but cannot send \"" + remoteFileName
                                + "\" file via ftp.");
            } catch (MessagingException ex) {
                System.out.println(ex.getMessage());
            }
        }
        client.logout();

    } catch (IOException ex) {
        System.out.println(ex.getMessage());
        errorFree = false;
    } finally {
        try {
            if (fis != null) {
                fis.close();
            }
            client.disconnect();
        } catch (IOException ex) {
            System.out.println(ex.getMessage());
        }
    }
    return errorFree;
}