Example usage for javax.mail MessagingException printStackTrace

List of usage examples for javax.mail MessagingException printStackTrace

Introduction

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

Prototype

public void printStackTrace() 

Source Link

Document

Prints this throwable and its backtrace to the standard error stream.

Usage

From source file:common.email.MailServiceImpl.java

/**
 * this method sends email using a given template
 * @param subject subject of a mail//  w w w.j  a v a  2 s .  c om
 * @param recipientEmail email receiver adress
 * @param mail mail text to send
 * @param from will be set
* @return true if send succeed
* @throws java.io.FileNotFoundException
 * @throws java.io.IOException
 */
protected boolean postMail(String subject, String recipientEmail, String from, String mail) throws IOException {
    try {
        Properties props = new Properties();
        //props.put("mailHost", mailHost);

        Session session = Session.getInstance(props);
        // construct the message
        javax.mail.Message msg = new javax.mail.internet.MimeMessage(session);
        if (from == null) {
            msg.setFrom();
        } else {
            try {
                msg.setFrom(new InternetAddress(from));
            } catch (MessagingException ex) {
                logger.error(ex);
            }
        }
        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipientEmail, false));
        msg.setSubject(subject);
        msg.setSentDate(new Date());
        //msg.setHeader("", user)
        msg.setDataHandler(new DataHandler(new ByteArrayDataSource(mail, "text/html; charset=UTF-8")));

        SMTPTransport t = (SMTPTransport) session.getTransport("smtp");
        t.connect(mailHost, user, password);
        Address[] a = msg.getAllRecipients();
        t.sendMessage(msg, a);
        t.close();
        return true;
    } catch (MessagingException ex) {
        logger.error(ex);
        ex.printStackTrace();
        return false;
    }

}

From source file:com.krawler.crm.contact.bizservice.ContactManagementServiceImpl.java

public JSONObject saveLogins(User creator, String loginurl, String companyId, String contactId, String emailId,
        Boolean setActive, String partnerNames) throws ServiceException, JSONException {
    JSONObject resultJsonObj = new JSONObject();
    JSONObject jsonData = new JSONObject();
    if (crmContactDAOObj.isEmailIdExist(emailId, companyId)) {
        resultJsonObj.put("mailIdExist", true);
    } else {/*from  w ww.j a v a  2  s  .  com*/
        resultJsonObj.put("success", false);
        KwlReturnObject kmsg = null;
        String username = creator.getFullname();
        String creatoremail = creator.getEmailID();
        String uuid = UUID.randomUUID().toString();
        String pswd = RandomStringUtils.random(8, true, true);//UUID.randomUUID().toString().substring(0, 8);
        String encodedpswd = getSHA1(pswd);
        if (!StringUtil.isNullOrEmpty(emailId))
            jsonData.put("emailId", emailId);
        if (!StringUtil.isNullOrEmpty(contactId))
            jsonData.put("contactId", contactId);
        if (!StringUtil.isNullOrEmpty(companyId))
            jsonData.put("companyId", companyId);
        jsonData.put("customerid", uuid);
        jsonData.put("pswd", encodedpswd);
        jsonData.put("setActive", setActive);
        kmsg = crmContactDAOObj.loginMail(jsonData);
        if (kmsg.isSuccessFlag()) {
            String passwordString = "\n\nUsername: " + emailId + " \nPassword: " + pswd;
            String passwordHtmlString = "<p>Username: " + emailId + " </p><p>Password: " + pswd + "</p>";
            String fname = ((Object[]) kmsg.getEntityList().get(1))[0] != null
                    ? ((Object[]) kmsg.getEntityList().get(1))[0].toString()
                    : "";
            String lname = ((Object[]) kmsg.getEntityList().get(1))[1] != null
                    ? ((Object[]) kmsg.getEntityList().get(1))[1].toString()
                    : "";
            Object name = (fname + " " + lname).trim();
            Object companyName = kmsg.getEntityList().toArray()[2];
            String msgMailInvite = "Dear %s,\n\n%s has created an account for you at %s." + passwordString
                    + "\n\nYou can log in at:\n%s\n\n\n - %s";
            String pmsg = String.format(msgMailInvite, name, companyName, username, loginurl, username);
            String msgMailInviteUsernamePassword = "<html><head><title>" + partnerNames
                    + " CRM - Your Account</title></head><style type='text/css'>"
                    + "a:link, a:visited, a:active {\n" + "    color: #03C;" + "}\n" + "body {\n"
                    + "   font-family: Arial, Helvetica, sans-serif;" + "   color: #000;"
                    + "   font-size: 13px;" + "}\n" + "</style><body>" + "   <div>"
                    + "      <p>Dear <strong>%s</strong>,</p>"
                    + "      <p>%s has created an account for you at %s.</p>" + passwordHtmlString
                    + "      <p>You can log in to your account at: <a href=%s>%s</a></p>"
                    + "      <br/><p> - %s</p>" + "   </div></body></html>";
            String htmlmsg = String.format(msgMailInviteUsernamePassword, name, username, companyName, loginurl,
                    loginurl, username);
            try {
                SendMailHandler.postMail(new String[] { emailId }, "Welcome to " + companyName, htmlmsg, pmsg,
                        creatoremail, companyName + " Admin");
            } catch (MessagingException e) {
                e.printStackTrace();
            } catch (UnsupportedEncodingException ue) {
                ue.printStackTrace();
            }
        }
        resultJsonObj.put("success", kmsg.isSuccessFlag());
        resultJsonObj.put("msg", kmsg.getMsg());
    }
    return resultJsonObj;
}

From source file:edu.hawaii.soest.hioos.storx.StorXDispatcher.java

/**
 * A method that executes the reading of data from the email account to the
 * RBNB server after all configuration of settings, connections to hosts,
 * and thread initiatizing occurs. This method contains the detailed code
 * for reading the data and interpreting the data files.
 *///from  w  ww  . jav  a  2 s  .co  m
protected boolean execute() {
    logger.debug("StorXDispatcher.execute() called.");
    boolean failed = true; // indicates overall success of execute()
    boolean messageProcessed = false; // indicates per message success

    // declare the account properties that will be pulled from the
    // email.account.properties.xml file
    String accountName = "";
    String server = "";
    String username = "";
    String password = "";
    String protocol = "";
    String dataMailbox = "";
    String processedMailbox = "";
    String prefetch = "";

    // fetch data from each sensor in the account list
    List accountList = this.xmlConfiguration.getList("account.accountName");

    for (Iterator aIterator = accountList.iterator(); aIterator.hasNext();) {

        int aIndex = accountList.indexOf(aIterator.next());

        // populate the email connection variables from the xml properties
        // file
        accountName = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").accountName");
        server = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").server");
        username = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").username");
        password = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").password");
        protocol = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").protocol");
        dataMailbox = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").dataMailbox");
        processedMailbox = (String) this.xmlConfiguration
                .getProperty("account(" + aIndex + ").processedMailbox");
        prefetch = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").prefetch");

        logger.debug("\n\nACCOUNT DETAILS: \n" + "accountName     : " + accountName + "\n"
                + "server          : " + server + "\n" + "username        : " + username + "\n"
                + "password        : " + password + "\n" + "protocol        : " + protocol + "\n"
                + "dataMailbox     : " + dataMailbox + "\n" + "processedMailbox: " + processedMailbox + "\n"
                + "prefetch        : " + prefetch + "\n");

        // get a connection to the mail server
        Properties props = System.getProperties();
        props.setProperty("mail.store.protocol", protocol);
        props.setProperty("mail.imaps.partialfetch", prefetch);

        try {

            // create the imaps mail session
            this.mailSession = Session.getDefaultInstance(props, null);
            this.mailStore = mailSession.getStore(protocol);

        } catch (NoSuchProviderException nspe) {

            try {
                // pause for 10 seconds
                logger.debug(
                        "There was a problem connecting to the IMAP server. " + "Waiting 10 seconds to retry.");
                Thread.sleep(10000L);
                this.mailStore = mailSession.getStore(protocol);

            } catch (NoSuchProviderException nspe2) {

                logger.debug("There was an error connecting to the mail server. The " + "message was: "
                        + nspe2.getMessage());
                nspe2.printStackTrace();
                failed = true;
                return !failed;

            } catch (InterruptedException ie) {

                logger.debug("The thread was interrupted: " + ie.getMessage());
                failed = true;
                return !failed;

            }

        }

        try {

            this.mailStore.connect(server, username, password);

            // get folder references for the inbox and processed data box
            Folder inbox = mailStore.getFolder(dataMailbox);
            inbox.open(Folder.READ_WRITE);

            Folder processed = this.mailStore.getFolder(processedMailbox);
            processed.open(Folder.READ_WRITE);

            Message[] msgs;
            while (!inbox.isOpen()) {
                inbox.open(Folder.READ_WRITE);

            }
            msgs = inbox.getMessages();

            List<Message> messages = new ArrayList<Message>();
            Collections.addAll(messages, msgs);

            // sort the messages found in the inbox by date sent
            Collections.sort(messages, new Comparator<Message>() {

                public int compare(Message message1, Message message2) {
                    int value = 0;
                    try {
                        value = message1.getSentDate().compareTo(message2.getSentDate());
                    } catch (MessagingException e) {
                        e.printStackTrace();
                    }
                    return value;

                }

            });

            logger.debug("Number of messages: " + messages.size());
            for (Message message : messages) {

                // Copy the message to ensure we have the full attachment
                MimeMessage mimeMessage = (MimeMessage) message;
                MimeMessage copiedMessage = new MimeMessage(mimeMessage);

                // determine the sensor serial number for this message
                String messageSubject = copiedMessage.getSubject();
                Date sentDate = copiedMessage.getSentDate();
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM");

                // The subfolder of the processed mail folder (e.g. 2016-12);
                String destinationFolder = formatter.format(sentDate);
                logger.debug("Message date: " + sentDate + "\tNumber: " + copiedMessage.getMessageNumber());
                String[] subjectParts = messageSubject.split("\\s");
                String loggerSerialNumber = "SerialNumber";
                if (subjectParts.length > 1) {
                    loggerSerialNumber = subjectParts[2];

                }

                // Do we have a data attachment? If not, there's no data to
                // process
                if (copiedMessage.isMimeType("multipart/mixed")) {

                    logger.debug("Message size: " + copiedMessage.getSize());

                    MimeMessageParser parser = new MimeMessageParser(copiedMessage);
                    try {
                        parser.parse();

                    } catch (Exception e) {
                        logger.error("Failed to parse the MIME message: " + e.getMessage());
                        continue;
                    }
                    ByteBuffer messageAttachment = ByteBuffer.allocate(256); // init only

                    logger.debug("Has attachments: " + parser.hasAttachments());
                    for (DataSource dataSource : parser.getAttachmentList()) {
                        if (StringUtils.isNotBlank(dataSource.getName())) {
                            logger.debug(
                                    "Attachment: " + dataSource.getName() + ", " + dataSource.getContentType());

                            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                            IOUtils.copy(dataSource.getInputStream(), outputStream);
                            messageAttachment = ByteBuffer.wrap(outputStream.toByteArray());

                        }
                    }

                    // We now have the attachment and serial number. Parse the attachment 
                    // for the data components, look up the storXSource based on the serial 
                    // number, and push the data to the DataTurbine

                    // parse the binary attachment
                    StorXParser storXParser = new StorXParser(messageAttachment);

                    // iterate through the parsed framesMap and handle each
                    // frame
                    // based on its instrument type
                    BasicHierarchicalMap framesMap = (BasicHierarchicalMap) storXParser.getFramesMap();

                    Collection frameCollection = framesMap.getAll("/frames/frame");
                    Iterator framesIterator = frameCollection.iterator();

                    while (framesIterator.hasNext()) {

                        BasicHierarchicalMap frameMap = (BasicHierarchicalMap) framesIterator.next();

                        // logger.debug(frameMap.toXMLString(1000));

                        String frameType = (String) frameMap.get("type");
                        String sensorSerialNumber = (String) frameMap.get("serialNumber");

                        // handle each instrument type
                        if (frameType.equals("HDR")) {
                            logger.debug("This is a header frame. Skipping it.");

                        } else if (frameType.equals("STX")) {

                            try {

                                // handle StorXSource
                                StorXSource source = (StorXSource) sourceMap.get(sensorSerialNumber);
                                // process the data using the StorXSource
                                // driver
                                messageProcessed = source.process(this.xmlConfiguration, frameMap);

                            } catch (ClassCastException cce) {

                            }

                        } else if (frameType.equals("SBE")) {

                            try {

                                // handle CTDSource
                                CTDSource source = (CTDSource) sourceMap.get(sensorSerialNumber);

                                // process the data using the CTDSource
                                // driver
                                messageProcessed = source.process(this.xmlConfiguration, frameMap);

                            } catch (ClassCastException cce) {

                            }

                        } else if (frameType.equals("NLB")) {

                            try {

                                // handle ISUSSource
                                ISUSSource source = (ISUSSource) sourceMap.get(sensorSerialNumber);
                                // process the data using the ISUSSource
                                // driver
                                messageProcessed = source.process(this.xmlConfiguration, frameMap);

                            } catch (ClassCastException cce) {

                            }

                        } else if (frameType.equals("NDB")) {

                            try {

                                // handle ISUSSource
                                ISUSSource source = (ISUSSource) sourceMap.get(sensorSerialNumber);
                                // process the data using the ISUSSource
                                // driver
                                messageProcessed = source.process(this.xmlConfiguration, frameMap);

                            } catch (ClassCastException cce) {

                            }

                        } else {

                            logger.debug("The frame type " + frameType + " is not recognized. Skipping it.");
                        }

                    } // end while()

                    if (this.sourceMap.get(loggerSerialNumber) != null) {

                        // Note: Use message (not copiedMessage) when setting flags 

                        if (!messageProcessed) {
                            logger.info("Failed to process message: " + "Message Number: "
                                    + message.getMessageNumber() + "  " + "Logger Serial:"
                                    + loggerSerialNumber);
                            // leave it in the inbox, flagged as seen (read)
                            message.setFlag(Flags.Flag.SEEN, true);
                            logger.debug("Saw message " + message.getMessageNumber());

                        } else {

                            // message processed successfully. Create a by-month sub folder if it doesn't exist
                            // Copy the message and flag it deleted
                            Folder destination = processed.getFolder(destinationFolder);
                            boolean created = destination.create(Folder.HOLDS_MESSAGES);
                            inbox.copyMessages(new Message[] { message }, destination);
                            message.setFlag(Flags.Flag.DELETED, true);
                            logger.debug("Deleted message " + message.getMessageNumber());
                        } // end if()

                    } else {
                        logger.debug("There is no configuration information for " + "the logger serial number "
                                + loggerSerialNumber + ". Please add the configuration to the "
                                + "email.account.properties.xml configuration file.");

                    } // end if()

                } else {
                    logger.debug("This is not a data email since there is no "
                            + "attachment. Skipping it. Subject: " + messageSubject);

                } // end if()

            } // end for()

            // expunge messages and close the mail server store once we're
            // done
            inbox.expunge();
            this.mailStore.close();

        } catch (MessagingException me) {
            try {
                this.mailStore.close();

            } catch (MessagingException me2) {
                failed = true;
                return !failed;

            }
            logger.info(
                    "There was an error reading the mail message. The " + "message was: " + me.getMessage());
            me.printStackTrace();
            failed = true;
            return !failed;

        } catch (IOException me) {
            try {
                this.mailStore.close();

            } catch (MessagingException me3) {
                failed = true;
                return !failed;

            }
            logger.info("There was an I/O error reading the message part. The " + "message was: "
                    + me.getMessage());
            me.printStackTrace();
            failed = true;
            return !failed;

        } catch (IllegalStateException ese) {
            try {
                this.mailStore.close();

            } catch (MessagingException me4) {
                failed = true;
                return !failed;

            }
            logger.info("There was an error reading messages from the folder. The " + "message was: "
                    + ese.getMessage());
            failed = true;
            return !failed;

        } finally {

            try {
                this.mailStore.close();

            } catch (MessagingException me2) {
                logger.debug("Couldn't close the mail store: " + me2.getMessage());

            }

        }

    }

    return !failed;
}

From source file:com.github.dougkelly88.FLIMPlateReaderGUI.SequencingClasses.GUIComponents.XYSequencing.java

public void sendEmail(String subject, String text, String toEmail) {

    // Recipient's email ID needs to be mentioned.
    String to = toEmail;//from   w w  w  .  j  av  a 2  s  .c om

    // Sender's email ID needs to be mentioned
    String from = "flimplatereader@gmail.com";

    // Assuming you are sending email from localhost
    String host = "localhost";

    // Get system properties
    //  Properties properties = System.getProperties();
    Properties properties = System.getProperties();

    // Setup mail server
    //properties.setProperty("mail.smtp.host", "10.101.3.229");
    properties.setProperty("mail.smtp.host", "smtp.gmail.com");
    properties.put("mail.smtp.port", "587");
    properties.setProperty("mail.user", "flimplatereader");
    properties.setProperty("mail.password", "flimimages");
    properties.put("mail.smtp.starttls.enable", "true");
    properties.put("mail.smtp.auth", "true"); //enable authentication

    final String pww = "flimimages";
    Session session;
    session = Session.getDefaultInstance(properties, new javax.mail.Authenticator() {
        protected javax.mail.PasswordAuthentication getPasswordAuthentication() {
            return new javax.mail.PasswordAuthentication("flimplatereader@gmail.com", pww);
        }
    });

    try {
        // Create a default MimeMessage object.
        MimeMessage message = new MimeMessage(session);

        // Set From: header field of the header.
        message.setFrom(new InternetAddress(from));

        // Set To: header field of the header.
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));

        // Set Subject: header field
        message.setSubject(subject);

        // Now set the actual message
        message.setText(text);

        // Send message
        Transport.send(message);
        System.out.println("Sent message successfully....");
    } catch (MessagingException mex) {
        mex.printStackTrace();
    }
}

From source file:org.socraticgrid.displaymaildata.DisplayMailDataHandler.java

public SetMessageResponseType archiveMessage(SetMessageRequestType request) {
    SetMessageResponseType response = new SetMessageResponseType();

    IMAPSSLStore sslStore = null;/* w  w  w. j  a  va 2 s. co  m*/
    Folder folder = null;
    Folder destinationFolder = null;
    Properties prop = initializeMailProperties();
    Session session = Session.getDefaultInstance(prop);

    // INPUT:  request.getUserId()
    //Get email address and password from LDAP
    String userId = request.getUserId();
    ContactDAO contactDAO = LdapService.getContactDAO();
    ContactDTO foundContact = new ContactDTO();
    List<ContactDTO> contacts = contactDAO.findAllContacts();
    for (ContactDTO contact : contacts) {
        if (contact.getUid() != null && contact.getUid().equals(request.getUserId())) {
            foundContact = contact;
            break;
        }
    }

    String userType = "";
    String[] access = new String[2];
    String userCName = foundContact.getCommonName();
    if (contacts.isEmpty()) {
        log.error("Contact record not found for user: " + userCName);
        response.setMessage("Contact record not found for user: " + userCName);
        response.setSuccessStatus(false);
        return response;
    }

    access = retrieveMailAccess(userCName, foundContact.getUid()); //TMN

    if ((access[0] == null) || access[0].isEmpty()) {
        log.error("Contact record not found for user: " + userId);
        response.setMessage("Contact record not found for user: " + userId);
        response.setSuccessStatus(false);
        return response;
    }

    //PROCESSING the action.
    // folder --> the current folder the msg being processed is in.
    // destinationFolder --> the destination folder where the msg will be moved.
    try {

        //----------------------------------
        // Determine/Set destination folder
        //----------------------------------
        if (request.getAction().equals("Archive")) {
            destinationFolder = getImapFolder(session, sslStore, access, "Archives");
        } else if (request.getAction().equals("Unarchive")) {
            destinationFolder = getImapFolder(session, sslStore, access, "INBOX");
        }
        destinationFolder.open(Folder.READ_WRITE);

        //----------------------------------
        // Set originating folder
        //----------------------------------
        folder = getImapFolder(session, sslStore, access,
                this.mapKmrLocationToImapFolder(request.getLocation(), this.host));
        folder.open(Folder.READ_WRITE);

        System.out.println(
                "===> DMD.archiveMessage: " + request.getAction() + "-ing for msgId=" + request.getMessageId()
                        + "\n===> from " + folder.getName() + " to folder=" + destinationFolder.getName());

        //--------------------------------------------
        // Find the message by the given Message-ID
        //--------------------------------------------
        IMAPMessage imapMessage = (IMAPMessage) findMsgByMessageId(folder, request.getMessageId());

        //--------------------------------------------
        // Process the message
        //--------------------------------------------
        if (imapMessage != null) {
            Message[] messages = new Message[] { imapMessage };
            folder.copyMessages(messages, destinationFolder);
            imapMessage.setFlag(Flags.Flag.DELETED, true);
            folder.expunge();

            System.out.println("===> DMD.archiveMessage: Done " + request.getAction() + " for msgId="
                    + request.getMessageId());

            response.setSuccessStatus(true);

        } else {
            String statMsg = "Msg NOT found for Message-ID=" + request.getMessageId();
            System.out.println("===> " + statMsg);

            response.setSuccessStatus(false);
            response.setMessage(statMsg);
        }

    } catch (Exception e) {
        log.error(e.getMessage());
        response.setMessage(
                "Error " + request.getAction() + " mail with Zimbra mail server: " + e.getMessage());
        response.setSuccessStatus(false);
        e.printStackTrace();
        return response;

    } finally {
        try {
            if ((folder != null) && folder.isOpen())
                folder.close(false);
            if ((destinationFolder != null) && destinationFolder.isOpen())
                destinationFolder.close(false);
        } catch (MessagingException me) {
            me.printStackTrace();
        }
    }

    return response;
}

From source file:org.socraticgrid.displaymaildata.DisplayMailDataHandler.java

public SetMessageResponseType deleteMessage(SetMessageRequestType request) {
    SetMessageResponseType response = new SetMessageResponseType();
    IMAPSSLStore sslStore = null;/*from w w  w.  j  av  a 2 s  . c  o m*/
    Folder sourceFolder = null;
    Folder targetFolder = null;
    Properties prop = initializeMailProperties();
    Session session = Session.getDefaultInstance(prop);

    //Get email address and password from LDAP
    String userId = request.getUserId();
    ContactDAO contactDAO = LdapService.getContactDAO();
    ContactDTO foundContact = new ContactDTO();
    List<ContactDTO> contacts = contactDAO.findAllContacts();
    for (ContactDTO contact : contacts) {
        if (contact.getUid() != null && contact.getUid().equals(request.getUserId())) {
            foundContact = contact;
            break;
        }
    }

    String userType = "";
    String[] access = new String[2];
    String userCName = foundContact.getCommonName();
    if (contacts.isEmpty()) {
        log.error("Contact record not found for user: " + userCName);
        response.setMessage("Contact record not found for user: " + userCName);
        response.setSuccessStatus(false);
        return response;
    }

    access = retrieveMailAccess(userCName, foundContact.getUid()); //TMN
    //        if (foundContact.getEmployeeNumber() != null) {
    //            userType = ITEM_ID_PROVIDER;
    //            access = retrieveMailAccess(userType, foundContact.getEmployeeNumber());
    //        }
    //        else {
    //            userType = ITEM_ID_PATIENT;
    //            access = retrieveMailAccess(userType, foundContact.getUid());
    //        }

    if ((access[0] == null) || access[0].isEmpty()) {
        log.error("Contact record not found for user: " + userId);
        response.setMessage("Contact record not found for user: " + userId);
        response.setSuccessStatus(false);
        return response;
    }

    try {

        //--------------------------
        // Set originating folder
        //--------------------------
        sourceFolder = getImapFolder(session, sslStore, access,
                this.mapKmrLocationToImapFolder(request.getLocation(), this.host));

        // Is this really needed if request comes in with location=UserTrash already?
        if (request.getAction().equals("Undelete")) {
            sourceFolder = getImapFolder(session, sslStore, access, "UserTrash");
        }
        sourceFolder.open(Folder.READ_WRITE);

        //--------------------------
        // Set destination folder
        //--------------------------
        if (request.getAction().equals("Delete")) {
            targetFolder = getImapFolder(session, sslStore, access, "UserTrash");
        }
        if (request.getAction().equals("DeleteForever")) {
            targetFolder = getImapFolder(session, sslStore, access, "AdminTrash");
        } else if (request.getAction().equals("Undelete")) {
            targetFolder = getImapFolder(session, sslStore, access, "INBOX");
        }
        targetFolder.open(Folder.READ_WRITE);

        //--------------------------------------------
        // Find the message by the given Message-ID
        //-------------------------------------------
        Message msg = this.findMsgByMessageId(sourceFolder, request.getMessageId());

        if (msg == null) {
            String errmsg = "Msg NOT found for Message-ID=" + request.getMessageId();
            System.out.println("===> deleteMessage: " + errmsg);

            response.setSuccessStatus(false);
            response.setMessage(errmsg);

        } else {

            //this.printMsgIdSubject(msg); //DBG printout

            //----------------------
            //copy to new folder
            //----------------------
            Message[] messages = new Message[] { msg };
            sourceFolder.copyMessages(messages, targetFolder);

            //----------------------
            //remove from old folder
            //----------------------
            msg.setFlag(Flags.Flag.DELETED, true);
            sourceFolder.expunge();

            response.setSuccessStatus(true);
        }

    } catch (Exception e) {
        log.error(e.getMessage());
        response.setMessage("Error archiving mail with Zimbra mail server: " + e.getMessage());
        response.setSuccessStatus(false);
        e.printStackTrace();
        return response;
    } finally {
        try {
            sourceFolder.close(false);
            targetFolder.close(false);
        } catch (MessagingException me) {
            me.printStackTrace();
        }
    }

    return response;
}

From source file:org.socraticgrid.displaymaildata.DisplayMailDataHandler.java

/**
 * Retrieve mail for user.//from  www.j  av a  2 s .c o m
 *
 * @param userType = "P" if logged in user is a provider
 *                   "T" if logged in user is a patient
 * @param userId = unique id of logged in user.
 * @param login = email server user name of logged in user.
 * @param pswd  = password of logged in user.
 * @param folderName = 
 * @param displayName = full name
 * @param onlyNew =
 *
 * @return
 * @throws java.lang.Exception
 */
//private  //DBG ONLY - REMOVE COMMENT MARKS
public List<SummaryData> retrieveMail(String userType, String userId, String patientId, String login,
        String pswd, String folderName, String patientName, boolean onlyNew, String mailHost, String mailUrl)
        throws Exception, DatatypeConfigurationException {
    List<SummaryData> dataList = new LinkedList<SummaryData>();
    IMAPSSLStore sslStore = null;
    IMAPFolder currentFolder = null;
    String folderToOpen = folderName;

    System.out.println("===> retrieveMail Incoming params:");
    System.out.println("===>     mailHost=" + mailHost);
    System.out.println("===>      mailUrl=" + mailUrl);
    System.out.println("===>    maillogin=" + login);
    System.out.println("===>   folderName=" + folderName);
    try {
        //Get session
        Session session = Session.getInstance(new Properties());
        URLName urlName = new URLName(mailUrl);
        //Get the sslStore
        sslStore = new IMAPSSLStore(session, urlName);
        sslStore.connect(mailHost, login, pswd);

        folderToOpen = this.mapKmrLocationToImapFolder(folderName, this.host);

        currentFolder = (IMAPFolder) sslStore.getFolder(folderToOpen);
        currentFolder.open(Folder.READ_ONLY);

        Message[] allMessages = currentFolder.getMessages();

        GregorianCalendar cal = new GregorianCalendar();

        System.out.println("====> FILTER PARAMS for Emails:");
        System.out.println("====>     folder = " + folderToOpen);
        System.out.println("====>     User   = " + login);
        //            System.out.println("====>     from   = "+ patientName +"/"+ patientEmail);
        //            System.out.println("====>     ptid   = "+ patientId);
        System.out.println("====> Total Emails found = " + allMessages.length);
        System.out.println();

        // TMN - CHECK SLOW PERFORMANCE ISSUE HERE:

        //Loop through each email and find ONLY the ones required for return.
        for (Message msg : allMessages) {
            if (msg == null) {
                continue;
            }

            // Keep this in case we want to search entire message
            //
            //                OutputStream os = new ByteArrayOutputStream();
            //                msg.writeTo(os);
            //                String msgContent = os.toString();

            SummaryData summaryData = new SummaryData();
            summaryData.setDataSource(DATA_SOURCE);

            String from = "";
            Address[] fromAddr = msg.getFrom();

            if (fromAddr != null && fromAddr.length > 0) {

                String fromFull = fromAddr[0].toString();
                from = getContactIdFromEmail(extractEmailAddressFromSender(fromFull));

                //System.out.println("retrieveMail: FROM=" + fromFull + " ldap.cn=" + from);

            }

            //------------------------------------------------------
            //FILTERING: Check to exclude email if
            //     0) patientId is passed in as a param
            // AND 1) email does NOT contain PATIENTID=<patientId>
            // AND 2) email FROM field <> patientName
            // AND 3) email FROM field <> patientEmail.
            //
            // because must becoming from EMR inbox and looking for emails
            // addressed to userId BUT only ABOUT or FROM patientId.
            //------------------------------------------------------

            summaryData.setFrom(from);
            summaryData.setAuthor(summaryData.getFrom());
            cal.setTime(msg.getReceivedDate());
            summaryData.setDateCreated(DatatypeFactory.newInstance().newXMLGregorianCalendar(cal));

            summaryData.setDescription(msg.getSubject());

            summaryData.setItemId(userType + userId + ITEM_ID_SEPARATER + msg.getFolder().getName()
                    + ITEM_ID_SEPARATER + msg.getHeader("Message-ID")[0]);

            //this.printMsgIdSubject(msg); //DBG printout

            boolean msgRead = msg.isSet(Flags.Flag.SEEN);
            addNameValue(summaryData.getItemValues(), ITEM_READ, String.valueOf(msgRead));

            boolean msgStar = msg.isSet(Flags.Flag.FLAGGED);
            if (msgStar) {
                addNameValue(summaryData.getItemValues(), ITEM_STARRED, "Starred");
            }

            addNameValue(summaryData.getItemValues(), ITEM_REPLIED,
                    String.valueOf(msg.isSet(Flags.Flag.ANSWERED)));
            addNameValue(summaryData.getItemValues(), "MESSAGE_TYPE", msg.getFolder().getName());
            if (onlyNew) {
                if (!msg.isSet(Flags.Flag.SEEN)) {
                    dataList.add(summaryData);
                }
            } else {
                dataList.add(summaryData);
            }
        }

    } catch (MessagingException me) {
        log.error("Error in processing email");
        me.printStackTrace();
    } finally {
        // Close connections

        if (currentFolder != null) {
            try {
                currentFolder.close(false);
            } catch (Exception e) {
            }
        }

        if (sslStore != null) {
            try {
                sslStore.close();
            } catch (Exception e) {
            }
        }
    }

    return dataList;
}

From source file:lucee.runtime.net.smtp.SMTPClient.java

public void _send(lucee.runtime.config.ConfigWeb config) throws MailException {

    long start = System.nanoTime();
    long _timeout = getTimeout(config, timeout);
    try {/* w  ww . ja v a 2  s.  c o m*/

        Proxy.start(proxyData);
        Log log = ((ConfigImpl) config).getLog("mail");
        // Server
        Server[] servers = config.getMailServers();
        if (host != null) {
            int prt;
            String usr, pwd;
            ServerImpl[] nServers = new ServerImpl[host.length];
            for (int i = 0; i < host.length; i++) {
                usr = null;
                pwd = null;
                prt = ServerImpl.DEFAULT_PORT;

                if (port > 0)
                    prt = port;
                if (!StringUtil.isEmpty(username)) {
                    usr = username;
                    pwd = password;
                }
                nServers[i] = toServerImpl(host[i], prt, usr, pwd, lifeTimespan, idleTimespan);
                if (ssl == SSL_YES)
                    nServers[i].setSSL(true);
                if (tls == TLS_YES)
                    nServers[i].setTLS(true);

            }
            servers = nServers;
        }
        if (servers.length == 0) {
            //return;
            throw new MailException("no SMTP Server defined");
        }

        boolean _ssl, _tls;
        for (int i = 0; i < servers.length; i++) {

            Server server = servers[i];
            String _username = null, _password = "";
            //int _port;

            // username/password

            if (server.hasAuthentication()) {
                _username = server.getUsername();
                _password = server.getPassword();
            }

            // tls
            if (tls != TLS_NONE)
                _tls = tls == TLS_YES;
            else
                _tls = ((ServerImpl) server).isTLS();

            // ssl
            if (ssl != SSL_NONE)
                _ssl = ssl == SSL_YES;
            else
                _ssl = ((ServerImpl) server).isSSL();

            MimeMessageAndSession msgSess;
            boolean recyleConnection = ((ServerImpl) server).reuseConnections();
            {//synchronized(LOCK) { no longer necessary we have a proxy lock now
                try {

                    msgSess = createMimeMessage(config, server.getHostName(), server.getPort(), _username,
                            _password, ((ServerImpl) server).getLifeTimeSpan(),
                            ((ServerImpl) server).getIdleTimeSpan(), _tls, _ssl, !recyleConnection);

                } catch (MessagingException e) {
                    // listener
                    listener(config, server, log, e, System.nanoTime() - start);
                    MailException me = new MailException(e.getMessage());
                    me.setStackTrace(e.getStackTrace());
                    throw me;
                }

                try {
                    SerializableObject lock = new SerializableObject();
                    SMTPSender sender = new SMTPSender(lock, msgSess, server.getHostName(), server.getPort(),
                            _username, _password, recyleConnection);
                    sender.start();
                    SystemUtil.wait(lock, _timeout);

                    if (!sender.isSent()) {
                        Throwable t = sender.getThrowable();
                        if (t != null)
                            throw Caster.toPageException(t);

                        // stop when still running
                        try {
                            if (sender.isAlive())
                                sender.stop();
                        } catch (Throwable t2) {
                        }

                        // after thread is stopped check sent flag again
                        if (!sender.isSent()) {
                            throw new MessagingException("timeout occurred after " + (_timeout / 1000)
                                    + " seconds while sending mail message");
                        }
                    }
                    clean(config, attachmentz);

                    listener(config, server, log, null, System.nanoTime() - start);
                    break;
                } catch (Exception e) {
                    e.printStackTrace();
                    if (i + 1 == servers.length) {

                        listener(config, server, log, e, System.nanoTime() - start);
                        MailException me = new MailException(
                                server.getHostName() + " " + ExceptionUtil.getStacktrace(e, true) + ":" + i);
                        me.setStackTrace(e.getStackTrace());

                        throw me;
                    }
                }
            }
        }
    } finally {
        Proxy.end();
    }
}

From source file:it.fub.jardin.server.DbUtils.java

public void sendRegistrationMail(MailUtility mailUtility, RegistrationInfo regInfo, Integer output)
        throws HiddenException {

    String mitt = mailUtility.getMailSmtpSender();
    String oggetto = "Jardin Manager - conferma registrazione";
    String password = RandomStringUtils.randomAlphanumeric(RandomUtils.nextInt(13) + 8);
    String testo = "Jardin Manager\n\n Conferma della registrazione al portale per l'utente "
            + regInfo.getNome() + " " + regInfo.getCognome() + "\n\n" + "Credenziali primo accesso:\n\n"
            + "Username: " + regInfo.getUsername() + "\n";

    if (output == 2) {
        testo = testo + "Password: " + password;
        updateUserCreds(regInfo, password);

        // invio email al sysadmin
        String sysadminMailText1 = "Jardin Manager\n\n Effettuata nuova registrazione per l'utente "
                + regInfo.getNome() + " " + regInfo.getCognome() + "\n\n" + "Credenziali primo accesso:\n\n"
                + "Username: " + regInfo.getUsername() + "\n" + "Password: inviata tramite mail all'utente";

        try {//from   ww  w .  ja  va  2  s.  co m

            mailUtility.sendMail(mailUtility.getMailSmtpSysadmin(), mitt,
                    "JardinManager - effettuata nuova registrazione con sola email", sysadminMailText1);
        } catch (MessagingException e) {
            e.printStackTrace();
            JardinLogger.error(regInfo.getUsername(),
                    "Invio email per nuova registrazione a sysadmin non riuscito!");
            JardinLogger.error(regInfo.getUsername(), "MessagingException: " + e.toString());
            // Log.info(e.toString());
        }
    } else if (output == 3) {
        testo = testo + "Prima parte della password: " + password;
        // la seconda parte della password  inviata tramite sms o telefonata
        String password2 = RandomStringUtils.randomAlphanumeric(RandomUtils.nextInt(13) + 8);

        JardinLogger.info(regInfo.getUsername(),
                "REGISTRAZIONE: all'utente " + regInfo.getUsername()
                        + " deve essere fornita la seconda parte della password: " + password2
                        + " (la prima parte  " + password + ")");

        updateUserCreds(regInfo, password + password2);

        testo = testo
                + "\n\n La seconda parte della password verr fornita tramite il numero di telefono indicato";

        // invio email al sysadmin
        String sysadminMailText2 = "Jardin Manager\n\n Effettuata nuova registrazione per l'utente"
                + regInfo.getNome() + " " + regInfo.getCognome() + "\n\n" + "Credenziali primo accesso:\n\n"
                + "Username: " + regInfo.getUsername() + "\n" + "Seconda parte della password: " + password2
                + "\n" + "(La prima parte della password  stata inviata tramite mail all'utente)\n\n"
                + "FORNIRE ALL'UTENTE LA SECONDA PARTE DELLA PASSWORD USANDO IL NUMERO DI TELEFONO "
                + regInfo.getTelefono() + "\n";

        try {

            mailUtility.sendMail(mailUtility.getMailSmtpSysadmin(), mitt,
                    "JardinManager - effettuata nuova registrazione con email e telefono", sysadminMailText2);
        } catch (MessagingException e) {
            e.printStackTrace();
            JardinLogger.error(regInfo.getUsername(),
                    "Invio email per nuova registrazione a sysadmin non riuscito!");
            JardinLogger.error(regInfo.getUsername(), "MessagingException: " + e.toString());
            // Log.info(e.toString());
        }
    }

    try {
        // invio mail all'utente
        mailUtility.sendMail(regInfo.getEmail(), mitt, oggetto, testo);

    } catch (MessagingException e) {
        e.printStackTrace();
        JardinLogger.error(regInfo.getUsername(), "Invio non riuscito!");
        JardinLogger.error(regInfo.getUsername(), "MessagingException: " + e.toString());
        // Log.info(e.toString());
    }

}

From source file:it.fub.jardin.server.DbUtils.java

public void notifyChanges(MailUtility mailUtility, final Integer resultsetId,
        final List<BaseModelData> newItemList, String operazione, String username)
        throws SQLException, HiddenException {
    Integer id_table = 0;//from   w  w w  .ja va 2s . c o  m
    String mitt = mailUtility.getMailSmtpSender();

    Connection connection = this.dbConnectionHandler.getConn();

    String query = "SELECT address_statement, data_statement, link_id, name FROM " + T_NOTIFY
            + " WHERE id_resultset = '" + resultsetId + "'";

    JardinLogger.debug(username, "query: " + query);

    ResultSet result = doQuery(connection, query);
    while (result.next()) {
        String testo = "";
        String address_statement = result.getString(1);
        String data_statement = result.getString(2);
        String bmdid = result.getString(3);
        String oggetto = result.getString(4);
        // JardinLogger.debug(username, "bmdid " + bmdid);

        for (BaseModelData record : newItemList) {
            // System.out.println("idrecord:"+record.get(bmdid)+":idrecord");
            if (record.get(bmdid) != null && record.get(bmdid) != "" && record.get(bmdid) != " "
                    && record.get(bmdid) != "\"\"") {
                id_table = Integer.valueOf(record.get(bmdid).toString());
                PreparedStatement psData = (PreparedStatement) connection.prepareStatement(data_statement);
                psData.setInt(1, id_table);
                ResultSet resultData = psData.executeQuery();
                while (resultData.next()) {
                    ResultSetMetaData md = resultData.getMetaData();
                    int count = md.getColumnCount();
                    for (int i = 1; i <= count; i++) {
                        testo += md.getColumnLabel(i) + ": " + resultData.getString(i) + "\n";
                    }
                    //            JardinLogger.debug(username, "\nmessaggio:\n" + testo);
                    testo += "\n";
                }

            } else {

                // gestire notifica per inserimento righe nel db
                testo += "nuovo record\n";
                Iterator itr = record.getPropertyNames().iterator();
                while (itr.hasNext()) {
                    String key = itr.next().toString();
                    testo += key + ": " + record.get(key) + "\n";
                    // System.out.print(key + ": " + record.get(key) + "\n");
                }
                testo += "\n\n";
                //          System.out.println(testo);
                JardinLogger.error(username, "Notifica non inviata perch  un inserimento!");
            }
        }

        PreparedStatement ps = (PreparedStatement) connection.prepareStatement(address_statement);
        // ps.setInt(1, id_table);
        ResultSet resultAddress = ps.executeQuery();
        while (resultAddress.next()) {
            JardinLogger.info(username, "Sending notification mail to: " + resultAddress.getString(1));
            if (!(resultAddress.getString(1) == null)) {
                try {
                    mailUtility.sendMail(resultAddress.getString(1), mitt, oggetto + " - " + operazione, testo);

                } catch (MessagingException e) {
                    e.printStackTrace();
                    JardinLogger.error(username, "Invio non riuscito!");
                    JardinLogger.error(username, "MessagingException: " + e.toString());
                    // Log.info(e.toString());
                }
                JardinLogger.info(username, "Invio riuscito!");
            } else {
                JardinLogger.error(username, "Errore invio mail: Mail non valida!");
            }
        }

    }
}