Example usage for javax.mail MessagingException toString

List of usage examples for javax.mail MessagingException toString

Introduction

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

Prototype

@Override
public synchronized String toString() 

Source Link

Document

Override toString method to provide information on nested exceptions.

Usage

From source file:it.unimi.di.big.mg4j.document.JavamailDocumentCollection.java

public Document document(final long index) throws IOException {
    try {//from  w  w w. ja v  a2  s  .c  o  m
        return new AbstractDocument() {
            // Can you believe that? Javamail numbers messages from 1...
            final Message message = folder.getMessage((int) (index + 1));

            public CharSequence title() {
                final String subject;
                try {
                    subject = message.getSubject();
                } catch (MessagingException e) {
                    throw new RuntimeException(e.toString());
                }
                if (subject == null)
                    return (CharSequence) factory.resolve(MetadataKeys.TITLE, factory.defaultMetadata);
                else
                    return subject;
            }

            public CharSequence uri() {
                try {
                    return folder.getURLName() + "#" + message.getMessageNumber();
                } catch (MessagingException e) {
                    throw new RuntimeException(e);
                }
            }

            private Reader joinAddresses(final Address address[]) {
                if (address == null)
                    return NullReader.getInstance();
                final MutableString s = new MutableString();
                if (address != null) {
                    for (int i = 0; i < address.length; i++) {
                        if (i > 0)
                            s.append(", ");
                        s.append(address[i]);
                    }
                }
                return new FastBufferedReader(s);
            }

            public Object content(final int field) throws IOException {
                factory.ensureFieldIndex(field);
                try {
                    switch (field) {
                    case 0: // body
                        // TODO: analyze multipart messages
                        Object content = null;
                        try {
                            content = message.getContent();
                        } catch (Exception e) {
                            LOGGER.warn("Message " + message.getMessageNumber()
                                    + " cannot be decoded; content will be empty", e);
                        }

                        if (content != null && content instanceof String)
                            return new StringReader((String) content);

                        return NullReader.getInstance();
                    case 1: // subject
                        return message.getSubject() == null ? NullReader.getInstance()
                                : new StringReader(message.getSubject());
                    case 2: // from
                        return joinAddresses(message.getFrom());
                    case 3: // to 
                        return joinAddresses(message.getRecipients(Message.RecipientType.TO));
                    case 4: // date
                        final String[] date = message.getHeader("date");
                        if (date == null || date.length == 0)
                            return NO_DATE;
                        final MailDateFormat mailDateFormat = new MailDateFormat();
                        try {
                            return mailDateFormat.parse(date[0]);
                        } catch (ParseException e) {
                            LOGGER.warn("Error parsing date " + date[0]);
                            return NO_DATE;
                        }

                    case 5: // cc
                        return joinAddresses(message.getRecipients(Message.RecipientType.CC));
                    case 6: // bcc
                        return joinAddresses(message.getRecipients(Message.RecipientType.BCC));
                    case 7: // content-type
                        return new StringReader(message.getContentType());
                    }
                } catch (MessagingException e) {
                    // A simple error
                    if (e instanceof AddressException) {
                        LOGGER.warn("Error while parsing address", e);
                        return NullReader.getInstance();
                    }
                    throw new IOException(e.toString());
                }
                throw new IllegalStateException();
            }

            public WordReader wordReader(final int field) {
                factory.ensureFieldIndex(field);
                return factory.wordReader;
            }
        };
    } catch (MessagingException e) {
        throw new IOException(e.toString());
    }
}

From source file:podd.resources.services.PublishProjectService.java

private void sendNotificationEmail() {
    try {/*from w  ww. j av  a2 s  . c o  m*/
        User pi = project.getPrincipalInvestigator();
        Set<String> ccAddresses;
        if (pi.equals(authenticatedUser)) {
            ccAddresses = Collections.emptySet();
        } else {
            ccAddresses = Collections.singleton(authenticatedUser.getEmail());
        }
        emailHandler.send(authenticatedUser.getEmail(), pi.getEmail(), ccAddresses, "PODD: Project Published",
                "The following project has been published in PODD and is now publicly available. \n\n"
                        + "   ID: " + project.getPid() + "\n" + "   Title: " + project.getLocalName() + "\n"
                        + "   Description: " + project.getLabel() + "\n\n"
                        + "You should receive an email notifying you of the projects persistant URL shortly.");
    } catch (MessagingException e) {
        final String msg = "Error sending email to " + authenticatedUser.getEmail() + ": " + e.getMessage()
                + "  ";
        LOGGER.error(msg, e);
        errorHandler.handleError(GENERAL_MESSAGE_ID, "Email Error", msg);
        auditLogHelper.auditAction(ERROR, authenticatedUser, "Publish Project Service: " + msg, e.toString());
    }
}

From source file:org.apache.james.mailetcontainer.lib.AbstractStateMailetProcessor.java

private void parseConfiguration() throws MessagingException, ConfigurationException {

    // load composite matchers if there are any
    Map<String, Matcher> compositeMatchers = new HashMap<String, Matcher>();
    loadCompositeMatchers(getState(), compositeMatchers, config.configurationsAt("matcher"));

    final List<HierarchicalConfiguration> mailetConfs = config.configurationsAt("mailet");

    // Loop through the mailet configuration, load
    // all of the matcher and mailets, and add
    // them to the processor.
    for (HierarchicalConfiguration c : mailetConfs) {
        // We need to set this because of correctly parsing comma
        String mailetClassName = c.getString("[@class]");
        String matcherName = c.getString("[@match]", null);
        String invertedMatcherName = c.getString("[@notmatch]", null);

        Mailet mailet;/*  w w w.ja v  a  2  s .c o  m*/
        Matcher matcher;

        try {

            if (matcherName != null && invertedMatcherName != null) {
                // if no matcher is configured throw an Exception
                throw new ConfigurationException("Please configure only match or nomatch per mailet");
            } else if (matcherName != null) {
                // try to load from compositeMatchers first
                matcher = compositeMatchers.get(matcherName);
                if (matcher == null) {
                    // no composite Matcher found, try to load it via
                    // MatcherLoader
                    matcher = matcherLoader.getMatcher(createMatcherConfig(matcherName));
                }
            } else if (invertedMatcherName != null) {
                // try to load from compositeMatchers first
                // matcherName is a known null value at this state
                matcher = compositeMatchers.get(matcherName);
                if (matcher == null) {
                    // no composite Matcher found, try to load it via
                    // MatcherLoader
                    matcher = matcherLoader.getMatcher(createMatcherConfig(invertedMatcherName));
                }
                matcher = new MatcherInverter(matcher);

            } else {
                // default matcher is All
                matcher = matcherLoader.getMatcher(createMatcherConfig("All"));
            }

            // The matcher itself should log that it's been inited.
            if (logger.isInfoEnabled()) {
                String infoBuffer = "Matcher " + matcherName + " instantiated.";
                logger.info(infoBuffer.toString());
            }
        } catch (MessagingException ex) {
            // **** Do better job printing out exception
            if (logger.isErrorEnabled()) {
                String errorBuffer = "Unable to init matcher " + matcherName + ": " + ex.toString();
                logger.error(errorBuffer.toString(), ex);
                if (ex.getNextException() != null) {
                    logger.error("Caused by nested exception: ", ex.getNextException());
                }
            }
            throw new ConfigurationException("Unable to init matcher " + matcherName, ex);
        }
        try {
            mailet = mailetLoader.getMailet(createMailetConfig(mailetClassName, c));
            if (logger.isInfoEnabled()) {
                String infoBuffer = "Mailet " + mailetClassName + " instantiated.";
                logger.info(infoBuffer.toString());
            }
        } catch (MessagingException ex) {
            // **** Do better job printing out exception
            if (logger.isErrorEnabled()) {
                String errorBuffer = "Unable to init mailet " + mailetClassName + ": " + ex.toString();
                logger.error(errorBuffer.toString(), ex);
                if (ex.getNextException() != null) {
                    logger.error("Caused by nested exception: ", ex.getNextException());
                }
            }
            throw new ConfigurationException("Unable to init mailet " + mailetClassName, ex);
        }

        if (matcher != null && mailet != null) {
            pairs.add(new MatcherMailetPair(matcher, mailet));
        } else {
            throw new ConfigurationException("Unable to load Mailet or Matcher");
        }
    }
}

From source file:net.fenyo.mail4hotspot.service.AdvancedServicesImpl.java

@Scheduled(fixedDelay = 5000)
public void sendNewMails() {
    try {/*from w w w . j  a  v a2s.co m*/
        synchronized (new_mails_working_sync) {
            if (new_mails_working == true)
                return;
            new_mails_working = true;
        }

        final List<AccountAndOutboxMail> accounts_and_mails = generalServices.getSentMails();

        for (AccountAndOutboxMail account_and_mail : accounts_and_mails) {
            boolean should_remove_user_id_processing = false;
            final User user = generalServices.getUserByAccount(account_and_mail.account);

            try {
                boolean abort_this_try = false;

                synchronized (userIdsProcessing) {
                    if (userIdsProcessing.contains(user.getId())) {
                        log.warn("account is currently processed");
                        abort_this_try = true;
                    } else {
                        should_remove_user_id_processing = true;
                        userIdsProcessing.add(user.getId());
                    }
                }

                final MailManager manager = new MailManager();
                if (abort_this_try == false) {
                    try {
                        manager.connectToRelay(account_and_mail.account.getProvider(),
                                account_and_mail.account.getUsername(), account_and_mail.account.getPassword());
                    } catch (final MessagingException ex) {
                        // le mieux serait de ne pas supprimer dans tous les cas, mais de compter le nombre de tentative et de les espacer
                        log.warn("can not connect to Relay: " + ex.toString());
                        abort_this_try = true;
                        generalServices.removeSentMail(account_and_mail.mail);
                        generalServices.sendInternalMailByAccount(account_and_mail.account,
                                "It was not possible to send your mail",
                                "An exception occured while sending your mail:\n" + ex.toString()
                                        + "\n\nthis mail has not been sent:\n-----\n" + "From: "
                                        + account_and_mail.account.getEmail() + "\n" + "To: "
                                        + account_and_mail.mail.getToAddr() + "\n" + "Cc: "
                                        + ((account_and_mail.mail.getCcAddr() == null) ? ""
                                                : account_and_mail.mail.getCcAddr())
                                        + "\n" + "Subject: " + account_and_mail.mail.getSubject() + "\n\n"
                                        + account_and_mail.mail.getContent() + "\n");
                    }
                }

                if (abort_this_try == false) {
                    generalServices.removeSentMail(account_and_mail.mail);

                    try {
                        final Address from_addr = new InternetAddress(account_and_mail.account.getEmail());
                        final Address[] to_addr = getAddressesFromString(account_and_mail.mail.getToAddr());
                        final Address[] cc_addr = getAddressesFromString(account_and_mail.mail.getCcAddr());

                        manager.sendMessage(from_addr, to_addr, cc_addr, account_and_mail.mail.getSubject(),
                                account_and_mail.mail.getContent());

                    } catch (final MessagingException ex) {
                        log.warn(ex.toString());

                        generalServices.sendInternalMailByAccount(account_and_mail.account,
                                "It was not possible to send your mail",
                                "An exception occured while sending your mail:\n" + ex.toString()
                                        + "\n\nthis mail has not been sent:\n-----\n" + "From: "
                                        + account_and_mail.account.getEmail() + "\n" + "To: "
                                        + account_and_mail.mail.getToAddr() + "\n" + "Cc: "
                                        + ((account_and_mail.mail.getCcAddr() == null) ? ""
                                                : account_and_mail.mail.getCcAddr())
                                        + "\n" + "Subject: " + account_and_mail.mail.getSubject() + "\n\n"
                                        + account_and_mail.mail.getContent() + "\n");

                    } finally {
                        try {
                            manager.disconnectRelay();
                        } catch (MessagingException ex) {
                            log.error(ex.toString());
                        }
                    }
                }
            } finally {
                synchronized (userIdsProcessing) {
                    if (should_remove_user_id_processing && userIdsProcessing.contains(user.getId()))
                        userIdsProcessing.remove(user.getId());
                }
            }
        }

    } finally {
        synchronized (new_mails_working_sync) {
            new_mails_working = false;
        }
    }
}

From source file:be.ibridge.kettle.job.entry.mail.JobEntryMail.java

public Result execute(Result result, int nr, Repository rep, Job parentJob) {
    LogWriter log = LogWriter.getInstance();

    File masterZipfile = null;//from  w ww . jav a 2s .c  o m

    // Send an e-mail...
    // create some properties and get the default Session
    Properties props = new Properties();
    if (Const.isEmpty(server)) {
        log.logError(toString(),
                "Unable to send the mail because the mail-server (SMTP host) is not specified");
        result.setNrErrors(1L);
        result.setResult(false);
        return result;
    }

    String protocol = "smtp";
    if (usingSecureAuthentication) {
        protocol = "smtps";
    }

    props.put("mail." + protocol + ".host", StringUtil.environmentSubstitute(server));
    if (!Const.isEmpty(port))
        props.put("mail." + protocol + ".port", StringUtil.environmentSubstitute(port));
    boolean debug = log.getLogLevel() >= LogWriter.LOG_LEVEL_DEBUG;

    if (debug)
        props.put("mail.debug", "true");

    if (usingAuthentication) {
        props.put("mail." + protocol + ".auth", "true");

        /*
        authenticator = new Authenticator()
        {
        protected PasswordAuthentication getPasswordAuthentication()
        {
            return new PasswordAuthentication(
                        StringUtil.environmentSubstitute(Const.NVL(authenticationUser, "")), 
                        StringUtil.environmentSubstitute(Const.NVL(authenticationPassword, ""))
                    );
        }
        };
        */
    }

    Session session = Session.getInstance(props);
    session.setDebug(debug);

    try {
        // create a message
        Message msg = new MimeMessage(session);

        String email_address = StringUtil.environmentSubstitute(replyAddress);
        if (!Const.isEmpty(email_address)) {
            msg.setFrom(new InternetAddress(email_address));
        } else {
            throw new MessagingException("reply e-mail address is not filled in");
        }

        // Split the mail-address: space separated
        String destinations[] = StringUtil.environmentSubstitute(destination).split(" ");
        InternetAddress[] address = new InternetAddress[destinations.length];
        for (int i = 0; i < destinations.length; i++)
            address[i] = new InternetAddress(destinations[i]);

        msg.setRecipients(Message.RecipientType.TO, address);

        if (!Const.isEmpty(destinationCc)) {
            // Split the mail-address Cc: space separated
            String destinationsCc[] = StringUtil.environmentSubstitute(destinationCc).split(" ");
            InternetAddress[] addressCc = new InternetAddress[destinationsCc.length];
            for (int i = 0; i < destinationsCc.length; i++)
                addressCc[i] = new InternetAddress(destinationsCc[i]);

            msg.setRecipients(Message.RecipientType.CC, addressCc);
        }

        if (!Const.isEmpty(destinationBCc)) {
            // Split the mail-address BCc: space separated
            String destinationsBCc[] = StringUtil.environmentSubstitute(destinationBCc).split(" ");
            InternetAddress[] addressBCc = new InternetAddress[destinationsBCc.length];
            for (int i = 0; i < destinationsBCc.length; i++)
                addressBCc[i] = new InternetAddress(destinationsBCc[i]);

            msg.setRecipients(Message.RecipientType.BCC, addressBCc);
        }

        msg.setSubject(StringUtil.environmentSubstitute(subject));
        msg.setSentDate(new Date());
        StringBuffer messageText = new StringBuffer();

        if (comment != null) {
            messageText.append(StringUtil.environmentSubstitute(comment)).append(Const.CR).append(Const.CR);
        }

        if (!onlySendComment) {
            messageText.append("Job:").append(Const.CR);
            messageText.append("-----").append(Const.CR);
            messageText.append("Name       : ").append(parentJob.getJobMeta().getName()).append(Const.CR);
            messageText.append("Directory  : ").append(parentJob.getJobMeta().getDirectory()).append(Const.CR);
            messageText.append("JobEntry   : ").append(getName()).append(Const.CR);
            messageText.append(Const.CR);
        }

        if (includeDate) {
            Value date = new Value("date", new Date());
            messageText.append("Message date: ").append(date.toString()).append(Const.CR).append(Const.CR);
        }
        if (!onlySendComment && result != null) {
            messageText.append("Previous result:").append(Const.CR);
            messageText.append("-----------------").append(Const.CR);
            messageText.append("Job entry nr         : ").append(result.getEntryNr()).append(Const.CR);
            messageText.append("Errors               : ").append(result.getNrErrors()).append(Const.CR);
            messageText.append("Lines read           : ").append(result.getNrLinesRead()).append(Const.CR);
            messageText.append("Lines written        : ").append(result.getNrLinesWritten()).append(Const.CR);
            messageText.append("Lines input          : ").append(result.getNrLinesInput()).append(Const.CR);
            messageText.append("Lines output         : ").append(result.getNrLinesOutput()).append(Const.CR);
            messageText.append("Lines updated        : ").append(result.getNrLinesUpdated()).append(Const.CR);
            messageText.append("Script exit status   : ").append(result.getExitStatus()).append(Const.CR);
            messageText.append("Result               : ").append(result.getResult()).append(Const.CR);
            messageText.append(Const.CR);
        }

        if (!onlySendComment && (!Const.isEmpty(StringUtil.environmentSubstitute(contactPerson))
                || !Const.isEmpty(StringUtil.environmentSubstitute(contactPhone)))) {
            messageText.append("Contact information :").append(Const.CR);
            messageText.append("---------------------").append(Const.CR);
            messageText.append("Person to contact : ").append(StringUtil.environmentSubstitute(contactPerson))
                    .append(Const.CR);
            messageText.append("Telephone number  : ").append(StringUtil.environmentSubstitute(contactPhone))
                    .append(Const.CR);
            messageText.append(Const.CR);
        }

        // Include the path to this job entry...
        if (!onlySendComment) {
            JobTracker jobTracker = parentJob.getJobTracker();
            if (jobTracker != null) {
                messageText.append("Path to this job entry:").append(Const.CR);
                messageText.append("------------------------").append(Const.CR);

                addBacktracking(jobTracker, messageText);
            }
        }

        Multipart parts = new MimeMultipart();
        MimeBodyPart part1 = new MimeBodyPart(); // put the text in the
        // 1st part
        part1.setText(messageText.toString());
        parts.addBodyPart(part1);
        if (includingFiles && result != null) {
            List resultFiles = result.getResultFilesList();
            if (resultFiles != null && resultFiles.size() > 0) {
                if (!zipFiles) {
                    // Add all files to the message...
                    //
                    for (Iterator iter = resultFiles.iterator(); iter.hasNext();) {
                        ResultFile resultFile = (ResultFile) iter.next();
                        FileObject file = resultFile.getFile();
                        if (file != null && file.exists()) {
                            boolean found = false;
                            for (int i = 0; i < fileType.length; i++) {
                                if (fileType[i] == resultFile.getType())
                                    found = true;
                            }
                            if (found) {
                                // create a data source
                                MimeBodyPart files = new MimeBodyPart();
                                URLDataSource fds = new URLDataSource(file.getURL());

                                // get a data Handler to manipulate this file type;
                                files.setDataHandler(new DataHandler(fds));
                                // include the file in the data source
                                files.setFileName(fds.getName());
                                // add the part with the file in the BodyPart();
                                parts.addBodyPart(files);

                                log.logBasic(toString(),
                                        "Added file '" + fds.getName() + "' to the mail message.");
                            }
                        }
                    }
                } else {
                    // create a single ZIP archive of all files
                    masterZipfile = new File(System.getProperty("java.io.tmpdir") + Const.FILE_SEPARATOR
                            + StringUtil.environmentSubstitute(zipFilename));
                    ZipOutputStream zipOutputStream = null;
                    try {
                        zipOutputStream = new ZipOutputStream(new FileOutputStream(masterZipfile));

                        for (Iterator iter = resultFiles.iterator(); iter.hasNext();) {
                            ResultFile resultFile = (ResultFile) iter.next();

                            boolean found = false;
                            for (int i = 0; i < fileType.length; i++) {
                                if (fileType[i] == resultFile.getType())
                                    found = true;
                            }
                            if (found) {
                                FileObject file = resultFile.getFile();
                                ZipEntry zipEntry = new ZipEntry(file.getName().getURI());
                                zipOutputStream.putNextEntry(zipEntry);

                                // Now put the content of this file into this archive...
                                BufferedInputStream inputStream = new BufferedInputStream(
                                        file.getContent().getInputStream());
                                int c;
                                while ((c = inputStream.read()) >= 0) {
                                    zipOutputStream.write(c);
                                }
                                inputStream.close();
                                zipOutputStream.closeEntry();

                                log.logBasic(toString(), "Added file '" + file.getName().getURI()
                                        + "' to the mail message in a zip archive.");
                            }
                        }
                    } catch (Exception e) {
                        log.logError(toString(), "Error zipping attachement files into file ["
                                + masterZipfile.getPath() + "] : " + e.toString());
                        log.logError(toString(), Const.getStackTracker(e));
                        result.setNrErrors(1);
                    } finally {
                        if (zipOutputStream != null) {
                            try {
                                zipOutputStream.finish();
                                zipOutputStream.close();
                            } catch (IOException e) {
                                log.logError(toString(),
                                        "Unable to close attachement zip file archive : " + e.toString());
                                log.logError(toString(), Const.getStackTracker(e));
                                result.setNrErrors(1);
                            }
                        }
                    }

                    // Now attach the master zip file to the message.
                    if (result.getNrErrors() == 0) {
                        // create a data source
                        MimeBodyPart files = new MimeBodyPart();
                        FileDataSource fds = new FileDataSource(masterZipfile);
                        // get a data Handler to manipulate this file type;
                        files.setDataHandler(new DataHandler(fds));
                        // include the file in th e data source
                        files.setFileName(fds.getName());
                        // add the part with the file in the BodyPart();
                        parts.addBodyPart(files);
                    }
                }
            }
        }
        msg.setContent(parts);

        Transport transport = null;
        try {
            transport = session.getTransport(protocol);
            if (usingAuthentication) {
                if (!Const.isEmpty(port)) {
                    transport.connect(StringUtil.environmentSubstitute(Const.NVL(server, "")),
                            Integer.parseInt(StringUtil.environmentSubstitute(Const.NVL(port, ""))),
                            StringUtil.environmentSubstitute(Const.NVL(authenticationUser, "")),
                            StringUtil.environmentSubstitute(Const.NVL(authenticationPassword, "")));
                } else {
                    transport.connect(StringUtil.environmentSubstitute(Const.NVL(server, "")),
                            StringUtil.environmentSubstitute(Const.NVL(authenticationUser, "")),
                            StringUtil.environmentSubstitute(Const.NVL(authenticationPassword, "")));
                }
            } else {
                transport.connect();
            }
            transport.sendMessage(msg, msg.getAllRecipients());
        } finally {
            if (transport != null)
                transport.close();
        }
    } catch (IOException e) {
        log.logError(toString(), "Problem while sending message: " + e.toString());
        result.setNrErrors(1);
    } catch (MessagingException mex) {
        log.logError(toString(), "Problem while sending message: " + mex.toString());
        result.setNrErrors(1);

        Exception ex = mex;
        do {
            if (ex instanceof SendFailedException) {
                SendFailedException sfex = (SendFailedException) ex;

                Address[] invalid = sfex.getInvalidAddresses();
                if (invalid != null) {
                    log.logError(toString(), "    ** Invalid Addresses");
                    for (int i = 0; i < invalid.length; i++) {
                        log.logError(toString(), "         " + invalid[i]);
                        result.setNrErrors(1);
                    }
                }

                Address[] validUnsent = sfex.getValidUnsentAddresses();
                if (validUnsent != null) {
                    log.logError(toString(), "    ** ValidUnsent Addresses");
                    for (int i = 0; i < validUnsent.length; i++) {
                        log.logError(toString(), "         " + validUnsent[i]);
                        result.setNrErrors(1);
                    }
                }

                Address[] validSent = sfex.getValidSentAddresses();
                if (validSent != null) {
                    //System.out.println("    ** ValidSent Addresses");
                    for (int i = 0; i < validSent.length; i++) {
                        log.logError(toString(), "         " + validSent[i]);
                        result.setNrErrors(1);
                    }
                }
            }
            if (ex instanceof MessagingException) {
                ex = ((MessagingException) ex).getNextException();
            } else {
                ex = null;
            }
        } while (ex != null);
    } finally {
        if (masterZipfile != null && masterZipfile.exists()) {
            masterZipfile.delete();
        }
    }

    if (result.getNrErrors() > 0) {
        result.setResult(false);
    } else {
        result.setResult(true);
    }

    return result;
}

From source file:com.panet.imeta.job.entries.mail.JobEntryMail.java

public Result execute(Result result, int nr, Repository rep, Job parentJob) {
    LogWriter log = LogWriter.getInstance();

    File masterZipfile = null;//from  ww w . j  a v  a  2s. c o  m

    // Send an e-mail...
    // create some properties and get the default Session
    Properties props = new Properties();
    if (Const.isEmpty(server)) {
        log.logError(toString(), Messages.getString("JobMail.Error.HostNotSpecified"));

        result.setNrErrors(1L);
        result.setResult(false);
        return result;
    }

    String protocol = "smtp";
    if (usingSecureAuthentication) {
        if (secureConnectionType.equals("TLS")) {
            // Allow TLS authentication
            props.put("mail.smtp.starttls.enable", "true");
        } else {

            protocol = "smtps";
            // required to get rid of a SSL exception :
            // nested exception is:
            // javax.net.ssl.SSLException: Unsupported record version
            // Unknown
            props.put("mail.smtps.quitwait", "false");
        }

    }

    props.put("mail." + protocol + ".host", environmentSubstitute(server));
    if (!Const.isEmpty(port))
        props.put("mail." + protocol + ".port", environmentSubstitute(port));
    boolean debug = log.getLogLevel() >= LogWriter.LOG_LEVEL_DEBUG;

    if (debug)
        props.put("mail.debug", "true");

    if (usingAuthentication) {
        props.put("mail." + protocol + ".auth", "true");

        /*
         * authenticator = new Authenticator() { protected
         * PasswordAuthentication getPasswordAuthentication() { return new
         * PasswordAuthentication(
         * StringUtil.environmentSubstitute(Const.NVL(authenticationUser,
         * "")),
         * StringUtil.environmentSubstitute(Const.NVL(authenticationPassword
         * , "")) ); } };
         */
    }

    Session session = Session.getInstance(props);
    session.setDebug(debug);

    try {
        // create a message
        Message msg = new MimeMessage(session);

        // set message priority
        if (usePriority) {
            String priority_int = "1";
            if (priority.equals("low")) {
                priority_int = "3";
            }
            if (priority.equals("normal")) {
                priority_int = "2";
            }

            msg.setHeader("X-Priority", priority_int); // (String)int
            // between 1= high
            // and 3 = low.
            msg.setHeader("Importance", importance);
            // seems to be needed for MS Outlook.
            // where it returns a string of high /normal /low.
        }

        // Set Mail sender (From)
        String sender_address = environmentSubstitute(replyAddress);
        if (!Const.isEmpty(sender_address)) {
            String sender_name = environmentSubstitute(replyName);
            if (!Const.isEmpty(sender_name))
                sender_address = sender_name + '<' + sender_address + '>';
            msg.setFrom(new InternetAddress(sender_address));
        } else {
            throw new MessagingException(Messages.getString("JobMail.Error.ReplyEmailNotFilled"));
        }

        // set Reply to addresses
        String reply_to_address = environmentSubstitute(replyToAddresses);
        if (!Const.isEmpty(reply_to_address)) {
            // Split the mail-address: space separated
            String[] reply_Address_List = environmentSubstitute(reply_to_address).split(" ");
            InternetAddress[] address = new InternetAddress[reply_Address_List.length];
            for (int i = 0; i < reply_Address_List.length; i++)
                address[i] = new InternetAddress(reply_Address_List[i]);
            msg.setReplyTo(address);
        }

        // Split the mail-address: space separated
        String destinations[] = environmentSubstitute(destination).split(" ");
        InternetAddress[] address = new InternetAddress[destinations.length];
        for (int i = 0; i < destinations.length; i++)
            address[i] = new InternetAddress(destinations[i]);
        msg.setRecipients(Message.RecipientType.TO, address);

        if (!Const.isEmpty(destinationCc)) {
            // Split the mail-address Cc: space separated
            String destinationsCc[] = environmentSubstitute(destinationCc).split(" ");
            InternetAddress[] addressCc = new InternetAddress[destinationsCc.length];
            for (int i = 0; i < destinationsCc.length; i++)
                addressCc[i] = new InternetAddress(destinationsCc[i]);

            msg.setRecipients(Message.RecipientType.CC, addressCc);
        }

        if (!Const.isEmpty(destinationBCc)) {
            // Split the mail-address BCc: space separated
            String destinationsBCc[] = environmentSubstitute(destinationBCc).split(" ");
            InternetAddress[] addressBCc = new InternetAddress[destinationsBCc.length];
            for (int i = 0; i < destinationsBCc.length; i++)
                addressBCc[i] = new InternetAddress(destinationsBCc[i]);

            msg.setRecipients(Message.RecipientType.BCC, addressBCc);
        }
        String realSubject = environmentSubstitute(subject);
        if (!Const.isEmpty(realSubject)) {
            msg.setSubject(realSubject);
        }

        msg.setSentDate(new Date());
        StringBuffer messageText = new StringBuffer();

        if (comment != null) {
            messageText.append(environmentSubstitute(comment)).append(Const.CR).append(Const.CR);
        }
        if (!onlySendComment) {

            messageText.append(Messages.getString("JobMail.Log.Comment.Job")).append(Const.CR);
            messageText.append("-----").append(Const.CR);
            messageText.append(Messages.getString("JobMail.Log.Comment.JobName") + "    : ")
                    .append(parentJob.getJobMeta().getName()).append(Const.CR);
            messageText.append(Messages.getString("JobMail.Log.Comment.JobDirectory") + "  : ")
                    .append(parentJob.getJobMeta().getDirectory()).append(Const.CR);
            messageText.append(Messages.getString("JobMail.Log.Comment.JobEntry") + "   : ").append(getName())
                    .append(Const.CR);
            messageText.append(Const.CR);
        }

        if (includeDate) {
            messageText.append(Const.CR).append(Messages.getString("JobMail.Log.Comment.MsgDate") + ": ")
                    .append(XMLHandler.date2string(new Date())).append(Const.CR).append(Const.CR);
        }
        if (!onlySendComment && result != null) {
            messageText.append(Messages.getString("JobMail.Log.Comment.PreviousResult") + ":").append(Const.CR);
            messageText.append("-----------------").append(Const.CR);
            messageText.append(Messages.getString("JobMail.Log.Comment.JobEntryNr") + "         : ")
                    .append(result.getEntryNr()).append(Const.CR);
            messageText.append(Messages.getString("JobMail.Log.Comment.Errors") + "               : ")
                    .append(result.getNrErrors()).append(Const.CR);
            messageText.append(Messages.getString("JobMail.Log.Comment.LinesRead") + "           : ")
                    .append(result.getNrLinesRead()).append(Const.CR);
            messageText.append(Messages.getString("JobMail.Log.Comment.LinesWritten") + "        : ")
                    .append(result.getNrLinesWritten()).append(Const.CR);
            messageText.append(Messages.getString("JobMail.Log.Comment.LinesInput") + "          : ")
                    .append(result.getNrLinesInput()).append(Const.CR);
            messageText.append(Messages.getString("JobMail.Log.Comment.LinesOutput") + "         : ")
                    .append(result.getNrLinesOutput()).append(Const.CR);
            messageText.append(Messages.getString("JobMail.Log.Comment.LinesUpdated") + "        : ")
                    .append(result.getNrLinesUpdated()).append(Const.CR);
            messageText.append(Messages.getString("JobMail.Log.Comment.Status") + "  : ")
                    .append(result.getExitStatus()).append(Const.CR);
            messageText.append(Messages.getString("JobMail.Log.Comment.Result") + "               : ")
                    .append(result.getResult()).append(Const.CR);
            messageText.append(Const.CR);
        }

        if (!onlySendComment && (!Const.isEmpty(environmentSubstitute(contactPerson))
                || !Const.isEmpty(environmentSubstitute(contactPhone)))) {
            messageText.append(Messages.getString("JobMail.Log.Comment.ContactInfo") + " :").append(Const.CR);
            messageText.append("---------------------").append(Const.CR);
            messageText.append(Messages.getString("JobMail.Log.Comment.PersonToContact") + " : ")
                    .append(environmentSubstitute(contactPerson)).append(Const.CR);
            messageText.append(Messages.getString("JobMail.Log.Comment.Tel") + "  : ")
                    .append(environmentSubstitute(contactPhone)).append(Const.CR);
            messageText.append(Const.CR);
        }

        // Include the path to this job entry...
        if (!onlySendComment) {
            JobTracker jobTracker = parentJob.getJobTracker();
            if (jobTracker != null) {
                messageText.append(Messages.getString("JobMail.Log.Comment.PathToJobentry") + ":")
                        .append(Const.CR);
                messageText.append("------------------------").append(Const.CR);

                addBacktracking(jobTracker, messageText);
            }
        }

        Multipart parts = new MimeMultipart();
        MimeBodyPart part1 = new MimeBodyPart(); // put the text in the
        // 1st part

        if (useHTML) {
            if (!Const.isEmpty(getEncoding())) {
                part1.setContent(messageText.toString(), "text/html; " + "charset=" + getEncoding());
            } else {
                part1.setContent(messageText.toString(), "text/html; " + "charset=ISO-8859-1");
            }

        }

        else
            part1.setText(messageText.toString());

        parts.addBodyPart(part1);

        if (includingFiles && result != null) {
            List<ResultFile> resultFiles = result.getResultFilesList();
            if (resultFiles != null && !resultFiles.isEmpty()) {
                if (!zipFiles) {
                    // Add all files to the message...
                    //
                    for (ResultFile resultFile : resultFiles) {
                        FileObject file = resultFile.getFile();
                        if (file != null && file.exists()) {
                            boolean found = false;
                            for (int i = 0; i < fileType.length; i++) {
                                if (fileType[i] == resultFile.getType())
                                    found = true;
                            }
                            if (found) {
                                // create a data source
                                MimeBodyPart files = new MimeBodyPart();
                                URLDataSource fds = new URLDataSource(file.getURL());

                                // get a data Handler to manipulate this
                                // file type;
                                files.setDataHandler(new DataHandler(fds));
                                // include the file in the data source
                                files.setFileName(file.getName().getBaseName());
                                // add the part with the file in the
                                // BodyPart();
                                parts.addBodyPart(files);

                                log.logBasic(toString(),
                                        "Added file '" + fds.getName() + "' to the mail message.");
                            }
                        }
                    }
                } else {
                    // create a single ZIP archive of all files
                    masterZipfile = new File(System.getProperty("java.io.tmpdir") + Const.FILE_SEPARATOR
                            + environmentSubstitute(zipFilename));
                    ZipOutputStream zipOutputStream = null;
                    try {
                        zipOutputStream = new ZipOutputStream(new FileOutputStream(masterZipfile));

                        for (ResultFile resultFile : resultFiles) {
                            boolean found = false;
                            for (int i = 0; i < fileType.length; i++) {
                                if (fileType[i] == resultFile.getType())
                                    found = true;
                            }
                            if (found) {
                                FileObject file = resultFile.getFile();
                                ZipEntry zipEntry = new ZipEntry(file.getName().getBaseName());
                                zipOutputStream.putNextEntry(zipEntry);

                                // Now put the content of this file into
                                // this archive...
                                BufferedInputStream inputStream = new BufferedInputStream(
                                        KettleVFS.getInputStream(file));
                                int c;
                                while ((c = inputStream.read()) >= 0) {
                                    zipOutputStream.write(c);
                                }
                                inputStream.close();
                                zipOutputStream.closeEntry();

                                log.logBasic(toString(), "Added file '" + file.getName().getURI()
                                        + "' to the mail message in a zip archive.");
                            }
                        }
                    } catch (Exception e) {
                        log.logError(toString(), "Error zipping attachement files into file ["
                                + masterZipfile.getPath() + "] : " + e.toString());
                        log.logError(toString(), Const.getStackTracker(e));
                        result.setNrErrors(1);
                    } finally {
                        if (zipOutputStream != null) {
                            try {
                                zipOutputStream.finish();
                                zipOutputStream.close();
                            } catch (IOException e) {
                                log.logError(toString(),
                                        "Unable to close attachement zip file archive : " + e.toString());
                                log.logError(toString(), Const.getStackTracker(e));
                                result.setNrErrors(1);
                            }
                        }
                    }

                    // Now attach the master zip file to the message.
                    if (result.getNrErrors() == 0) {
                        // create a data source
                        MimeBodyPart files = new MimeBodyPart();
                        FileDataSource fds = new FileDataSource(masterZipfile);
                        // get a data Handler to manipulate this file type;
                        files.setDataHandler(new DataHandler(fds));
                        // include the file in th e data source
                        files.setFileName(fds.getName());
                        // add the part with the file in the BodyPart();
                        parts.addBodyPart(files);
                    }
                }
            }
        }
        msg.setContent(parts);

        Transport transport = null;
        try {
            transport = session.getTransport(protocol);
            if (usingAuthentication) {
                if (!Const.isEmpty(port)) {
                    transport.connect(environmentSubstitute(Const.NVL(server, "")),
                            Integer.parseInt(environmentSubstitute(Const.NVL(port, ""))),
                            environmentSubstitute(Const.NVL(authenticationUser, "")),
                            environmentSubstitute(Const.NVL(authenticationPassword, "")));
                } else {
                    transport.connect(environmentSubstitute(Const.NVL(server, "")),
                            environmentSubstitute(Const.NVL(authenticationUser, "")),
                            environmentSubstitute(Const.NVL(authenticationPassword, "")));
                }
            } else {
                transport.connect();
            }
            transport.sendMessage(msg, msg.getAllRecipients());
        } finally {
            if (transport != null)
                transport.close();
        }
    } catch (IOException e) {
        log.logError(toString(), "Problem while sending message: " + e.toString());
        result.setNrErrors(1);
    } catch (MessagingException mex) {
        log.logError(toString(), "Problem while sending message: " + mex.toString());
        result.setNrErrors(1);

        Exception ex = mex;
        do {
            if (ex instanceof SendFailedException) {
                SendFailedException sfex = (SendFailedException) ex;

                Address[] invalid = sfex.getInvalidAddresses();
                if (invalid != null) {
                    log.logError(toString(), "    ** Invalid Addresses");
                    for (int i = 0; i < invalid.length; i++) {
                        log.logError(toString(), "         " + invalid[i]);
                        result.setNrErrors(1);
                    }
                }

                Address[] validUnsent = sfex.getValidUnsentAddresses();
                if (validUnsent != null) {
                    log.logError(toString(), "    ** ValidUnsent Addresses");
                    for (int i = 0; i < validUnsent.length; i++) {
                        log.logError(toString(), "         " + validUnsent[i]);
                        result.setNrErrors(1);
                    }
                }

                Address[] validSent = sfex.getValidSentAddresses();
                if (validSent != null) {
                    // System.out.println("    ** ValidSent Addresses");
                    for (int i = 0; i < validSent.length; i++) {
                        log.logError(toString(), "         " + validSent[i]);
                        result.setNrErrors(1);
                    }
                }
            }
            if (ex instanceof MessagingException) {
                ex = ((MessagingException) ex).getNextException();
            } else {
                ex = null;
            }
        } while (ex != null);
    } finally {
        if (masterZipfile != null && masterZipfile.exists()) {
            masterZipfile.delete();
        }
    }

    if (result.getNrErrors() > 0) {
        result.setResult(false);
    } else {
        result.setResult(true);
    }

    return result;
}

From source file:org.pentaho.di.job.entries.mail.JobEntryMail.java

public Result execute(Result result, int nr) {
    File masterZipfile = null;//from   w  w  w .  j  av a 2 s.  c  o m

    // Send an e-mail...
    // create some properties and get the default Session
    Properties props = new Properties();
    if (Const.isEmpty(server)) {
        logError(BaseMessages.getString(PKG, "JobMail.Error.HostNotSpecified"));

        result.setNrErrors(1L);
        result.setResult(false);
        return result;
    }

    String protocol = "smtp";
    if (usingSecureAuthentication) {
        if (secureConnectionType.equals("TLS")) {
            // Allow TLS authentication
            props.put("mail.smtp.starttls.enable", "true");
        } else {

            protocol = "smtps";
            // required to get rid of a SSL exception :
            // nested exception is:
            // javax.net.ssl.SSLException: Unsupported record version Unknown
            props.put("mail.smtps.quitwait", "false");
        }

    }

    props.put("mail." + protocol + ".host", environmentSubstitute(server));
    if (!Const.isEmpty(port)) {
        props.put("mail." + protocol + ".port", environmentSubstitute(port));
    }

    if (log.isDebug()) {
        props.put("mail.debug", "true");
    }

    if (usingAuthentication) {
        props.put("mail." + protocol + ".auth", "true");

        /*
         * authenticator = new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new
         * PasswordAuthentication( StringUtil.environmentSubstitute(Const.NVL(authenticationUser, "")),
         * StringUtil.environmentSubstitute(Const.NVL(authenticationPassword, "")) ); } };
         */
    }

    Session session = Session.getInstance(props);
    session.setDebug(log.isDebug());

    try {
        // create a message
        Message msg = new MimeMessage(session);

        // set message priority
        if (usePriority) {
            String priority_int = "1";
            if (priority.equals("low")) {
                priority_int = "3";
            }
            if (priority.equals("normal")) {
                priority_int = "2";
            }

            msg.setHeader("X-Priority", priority_int); // (String)int between 1= high and 3 = low.
            msg.setHeader("Importance", importance);
            // seems to be needed for MS Outlook.
            // where it returns a string of high /normal /low.
            msg.setHeader("Sensitivity", sensitivity);
            // Possible values are normal, personal, private, company-confidential

        }

        // Set Mail sender (From)
        String sender_address = environmentSubstitute(replyAddress);
        if (!Const.isEmpty(sender_address)) {
            String sender_name = environmentSubstitute(replyName);
            if (!Const.isEmpty(sender_name)) {
                sender_address = sender_name + '<' + sender_address + '>';
            }
            msg.setFrom(new InternetAddress(sender_address));
        } else {
            throw new MessagingException(BaseMessages.getString(PKG, "JobMail.Error.ReplyEmailNotFilled"));
        }

        // set Reply to addresses
        String reply_to_address = environmentSubstitute(replyToAddresses);
        if (!Const.isEmpty(reply_to_address)) {
            // Split the mail-address: space separated
            String[] reply_Address_List = environmentSubstitute(reply_to_address).split(" ");
            InternetAddress[] address = new InternetAddress[reply_Address_List.length];
            for (int i = 0; i < reply_Address_List.length; i++) {
                address[i] = new InternetAddress(reply_Address_List[i]);
            }
            msg.setReplyTo(address);
        }

        // Split the mail-address: space separated
        String[] destinations = environmentSubstitute(destination).split(" ");
        InternetAddress[] address = new InternetAddress[destinations.length];
        for (int i = 0; i < destinations.length; i++) {
            address[i] = new InternetAddress(destinations[i]);
        }
        msg.setRecipients(Message.RecipientType.TO, address);

        String realCC = environmentSubstitute(getDestinationCc());
        if (!Const.isEmpty(realCC)) {
            // Split the mail-address Cc: space separated
            String[] destinationsCc = realCC.split(" ");
            InternetAddress[] addressCc = new InternetAddress[destinationsCc.length];
            for (int i = 0; i < destinationsCc.length; i++) {
                addressCc[i] = new InternetAddress(destinationsCc[i]);
            }

            msg.setRecipients(Message.RecipientType.CC, addressCc);
        }

        String realBCc = environmentSubstitute(getDestinationBCc());
        if (!Const.isEmpty(realBCc)) {
            // Split the mail-address BCc: space separated
            String[] destinationsBCc = realBCc.split(" ");
            InternetAddress[] addressBCc = new InternetAddress[destinationsBCc.length];
            for (int i = 0; i < destinationsBCc.length; i++) {
                addressBCc[i] = new InternetAddress(destinationsBCc[i]);
            }

            msg.setRecipients(Message.RecipientType.BCC, addressBCc);
        }
        String realSubject = environmentSubstitute(subject);
        if (!Const.isEmpty(realSubject)) {
            msg.setSubject(realSubject);
        }

        msg.setSentDate(new Date());
        StringBuffer messageText = new StringBuffer();
        String endRow = isUseHTML() ? "<br>" : Const.CR;
        String realComment = environmentSubstitute(comment);
        if (!Const.isEmpty(realComment)) {
            messageText.append(realComment).append(Const.CR).append(Const.CR);
        }
        if (!onlySendComment) {

            messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.Job")).append(endRow);
            messageText.append("-----").append(endRow);
            messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.JobName") + "    : ")
                    .append(parentJob.getJobMeta().getName()).append(endRow);
            messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.JobDirectory") + "  : ")
                    .append(parentJob.getJobMeta().getRepositoryDirectory()).append(endRow);
            messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.JobEntry") + "   : ")
                    .append(getName()).append(endRow);
            messageText.append(Const.CR);
        }

        if (includeDate) {
            messageText.append(endRow).append(BaseMessages.getString(PKG, "JobMail.Log.Comment.MsgDate") + ": ")
                    .append(XMLHandler.date2string(new Date())).append(endRow).append(endRow);
        }
        if (!onlySendComment && result != null) {
            messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.PreviousResult") + ":")
                    .append(endRow);
            messageText.append("-----------------").append(endRow);
            messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.JobEntryNr") + "         : ")
                    .append(result.getEntryNr()).append(endRow);
            messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.Errors") + "               : ")
                    .append(result.getNrErrors()).append(endRow);
            messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.LinesRead") + "           : ")
                    .append(result.getNrLinesRead()).append(endRow);
            messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.LinesWritten") + "        : ")
                    .append(result.getNrLinesWritten()).append(endRow);
            messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.LinesInput") + "          : ")
                    .append(result.getNrLinesInput()).append(endRow);
            messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.LinesOutput") + "         : ")
                    .append(result.getNrLinesOutput()).append(endRow);
            messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.LinesUpdated") + "        : ")
                    .append(result.getNrLinesUpdated()).append(endRow);
            messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.LinesRejected") + "       : ")
                    .append(result.getNrLinesRejected()).append(endRow);
            messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.Status") + "  : ")
                    .append(result.getExitStatus()).append(endRow);
            messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.Result") + "               : ")
                    .append(result.getResult()).append(endRow);
            messageText.append(endRow);
        }

        if (!onlySendComment && (!Const.isEmpty(environmentSubstitute(contactPerson))
                || !Const.isEmpty(environmentSubstitute(contactPhone)))) {
            messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.ContactInfo") + " :")
                    .append(endRow);
            messageText.append("---------------------").append(endRow);
            messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.PersonToContact") + " : ")
                    .append(environmentSubstitute(contactPerson)).append(endRow);
            messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.Tel") + "  : ")
                    .append(environmentSubstitute(contactPhone)).append(endRow);
            messageText.append(endRow);
        }

        // Include the path to this job entry...
        if (!onlySendComment) {
            JobTracker jobTracker = parentJob.getJobTracker();
            if (jobTracker != null) {
                messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.PathToJobentry") + ":")
                        .append(endRow);
                messageText.append("------------------------").append(endRow);

                addBacktracking(jobTracker, messageText);
                if (isUseHTML()) {
                    messageText.replace(0, messageText.length(),
                            messageText.toString().replace(Const.CR, endRow));
                }
            }
        }

        MimeMultipart parts = new MimeMultipart();
        MimeBodyPart part1 = new MimeBodyPart(); // put the text in the
        // Attached files counter
        int nrattachedFiles = 0;

        // 1st part

        if (useHTML) {
            if (!Const.isEmpty(getEncoding())) {
                part1.setContent(messageText.toString(), "text/html; " + "charset=" + getEncoding());
            } else {
                part1.setContent(messageText.toString(), "text/html; " + "charset=ISO-8859-1");
            }
        } else {
            part1.setText(messageText.toString());
        }

        parts.addBodyPart(part1);

        if (includingFiles && result != null) {
            List<ResultFile> resultFiles = result.getResultFilesList();
            if (resultFiles != null && !resultFiles.isEmpty()) {
                if (!zipFiles) {
                    // Add all files to the message...
                    //
                    for (ResultFile resultFile : resultFiles) {
                        FileObject file = resultFile.getFile();
                        if (file != null && file.exists()) {
                            boolean found = false;
                            for (int i = 0; i < fileType.length; i++) {
                                if (fileType[i] == resultFile.getType()) {
                                    found = true;
                                }
                            }
                            if (found) {
                                // create a data source
                                MimeBodyPart files = new MimeBodyPart();
                                URLDataSource fds = new URLDataSource(file.getURL());

                                // get a data Handler to manipulate this file type;
                                files.setDataHandler(new DataHandler(fds));
                                // include the file in the data source
                                files.setFileName(file.getName().getBaseName());

                                // insist on base64 to preserve line endings
                                files.addHeader("Content-Transfer-Encoding", "base64");

                                // add the part with the file in the BodyPart();
                                parts.addBodyPart(files);
                                nrattachedFiles++;
                                logBasic("Added file '" + fds.getName() + "' to the mail message.");
                            }
                        }
                    }
                } else {
                    // create a single ZIP archive of all files
                    masterZipfile = new File(System.getProperty("java.io.tmpdir") + Const.FILE_SEPARATOR
                            + environmentSubstitute(zipFilename));
                    ZipOutputStream zipOutputStream = null;
                    try {
                        zipOutputStream = new ZipOutputStream(new FileOutputStream(masterZipfile));

                        for (ResultFile resultFile : resultFiles) {
                            boolean found = false;
                            for (int i = 0; i < fileType.length; i++) {
                                if (fileType[i] == resultFile.getType()) {
                                    found = true;
                                }
                            }
                            if (found) {
                                FileObject file = resultFile.getFile();
                                ZipEntry zipEntry = new ZipEntry(file.getName().getBaseName());
                                zipOutputStream.putNextEntry(zipEntry);

                                // Now put the content of this file into this archive...
                                BufferedInputStream inputStream = new BufferedInputStream(
                                        KettleVFS.getInputStream(file));
                                try {
                                    int c;
                                    while ((c = inputStream.read()) >= 0) {
                                        zipOutputStream.write(c);
                                    }
                                } finally {
                                    inputStream.close();
                                }
                                zipOutputStream.closeEntry();
                                nrattachedFiles++;
                                logBasic("Added file '" + file.getName().getURI()
                                        + "' to the mail message in a zip archive.");
                            }
                        }
                    } catch (Exception e) {
                        logError("Error zipping attachement files into file [" + masterZipfile.getPath()
                                + "] : " + e.toString());
                        logError(Const.getStackTracker(e));
                        result.setNrErrors(1);
                    } finally {
                        if (zipOutputStream != null) {
                            try {
                                zipOutputStream.finish();
                                zipOutputStream.close();
                            } catch (IOException e) {
                                logError("Unable to close attachement zip file archive : " + e.toString());
                                logError(Const.getStackTracker(e));
                                result.setNrErrors(1);
                            }
                        }
                    }

                    // Now attach the master zip file to the message.
                    if (result.getNrErrors() == 0) {
                        // create a data source
                        MimeBodyPart files = new MimeBodyPart();
                        FileDataSource fds = new FileDataSource(masterZipfile);
                        // get a data Handler to manipulate this file type;
                        files.setDataHandler(new DataHandler(fds));
                        // include the file in the data source
                        files.setFileName(fds.getName());
                        // add the part with the file in the BodyPart();
                        parts.addBodyPart(files);
                    }
                }
            }
        }

        int nrEmbeddedImages = 0;
        if (embeddedimages != null && embeddedimages.length > 0) {
            FileObject imageFile = null;
            for (int i = 0; i < embeddedimages.length; i++) {
                String realImageFile = environmentSubstitute(embeddedimages[i]);
                String realcontenID = environmentSubstitute(contentids[i]);
                if (messageText.indexOf("cid:" + realcontenID) < 0) {
                    if (log.isDebug()) {
                        log.logDebug("Image [" + realImageFile + "] is not used in message body!");
                    }
                } else {
                    try {
                        boolean found = false;
                        imageFile = KettleVFS.getFileObject(realImageFile, this);
                        if (imageFile.exists() && imageFile.getType() == FileType.FILE) {
                            found = true;
                        } else {
                            log.logError("We can not find [" + realImageFile + "] or it is not a file");
                        }
                        if (found) {
                            // Create part for the image
                            MimeBodyPart messageBodyPart = new MimeBodyPart();
                            // Load the image
                            URLDataSource fds = new URLDataSource(imageFile.getURL());
                            messageBodyPart.setDataHandler(new DataHandler(fds));
                            // Setting the header
                            messageBodyPart.setHeader("Content-ID", "<" + realcontenID + ">");
                            // Add part to multi-part
                            parts.addBodyPart(messageBodyPart);
                            nrEmbeddedImages++;
                            log.logBasic("Image '" + fds.getName() + "' was embedded in message.");
                        }
                    } catch (Exception e) {
                        log.logError(
                                "Error embedding image [" + realImageFile + "] in message : " + e.toString());
                        log.logError(Const.getStackTracker(e));
                        result.setNrErrors(1);
                    } finally {
                        if (imageFile != null) {
                            try {
                                imageFile.close();
                            } catch (Exception e) { /* Ignore */
                            }
                        }
                    }
                }
            }
        }

        if (nrEmbeddedImages > 0 && nrattachedFiles == 0) {
            // If we need to embedd images...
            // We need to create a "multipart/related" message.
            // otherwise image will appear as attached file
            parts.setSubType("related");
        }
        // put all parts together
        msg.setContent(parts);

        Transport transport = null;
        try {
            transport = session.getTransport(protocol);
            String authPass = getPassword(authenticationPassword);

            if (usingAuthentication) {
                if (!Const.isEmpty(port)) {
                    transport.connect(environmentSubstitute(Const.NVL(server, "")),
                            Integer.parseInt(environmentSubstitute(Const.NVL(port, ""))),
                            environmentSubstitute(Const.NVL(authenticationUser, "")), authPass);
                } else {
                    transport.connect(environmentSubstitute(Const.NVL(server, "")),
                            environmentSubstitute(Const.NVL(authenticationUser, "")), authPass);
                }
            } else {
                transport.connect();
            }
            transport.sendMessage(msg, msg.getAllRecipients());
        } finally {
            if (transport != null) {
                transport.close();
            }
        }
    } catch (IOException e) {
        logError("Problem while sending message: " + e.toString());
        result.setNrErrors(1);
    } catch (MessagingException mex) {
        logError("Problem while sending message: " + mex.toString());
        result.setNrErrors(1);

        Exception ex = mex;
        do {
            if (ex instanceof SendFailedException) {
                SendFailedException sfex = (SendFailedException) ex;

                Address[] invalid = sfex.getInvalidAddresses();
                if (invalid != null) {
                    logError("    ** Invalid Addresses");
                    for (int i = 0; i < invalid.length; i++) {
                        logError("         " + invalid[i]);
                        result.setNrErrors(1);
                    }
                }

                Address[] validUnsent = sfex.getValidUnsentAddresses();
                if (validUnsent != null) {
                    logError("    ** ValidUnsent Addresses");
                    for (int i = 0; i < validUnsent.length; i++) {
                        logError("         " + validUnsent[i]);
                        result.setNrErrors(1);
                    }
                }

                Address[] validSent = sfex.getValidSentAddresses();
                if (validSent != null) {
                    // System.out.println("    ** ValidSent Addresses");
                    for (int i = 0; i < validSent.length; i++) {
                        logError("         " + validSent[i]);
                        result.setNrErrors(1);
                    }
                }
            }
            if (ex instanceof MessagingException) {
                ex = ((MessagingException) ex).getNextException();
            } else {
                ex = null;
            }
        } while (ex != null);
    } finally {
        if (masterZipfile != null && masterZipfile.exists()) {
            masterZipfile.delete();
        }
    }

    if (result.getNrErrors() > 0) {
        result.setResult(false);
    } else {
        result.setResult(true);
    }

    return result;
}

From source file:org.masukomi.aspirin.core.RemoteDelivery.java

/**
 * Insert the method's description here. Creation date: (2/25/00 1:14:18 AM)
 * //from  w  w w.  j  ava 2  s  .  com
 * @param mail
 *            org.apache.james.core.MailImpl
 * @param exception
 *            java.lang.Exception
 * @param boolean
 *            permanent
 * @return boolean Whether the message failed fully and can be deleted
 */
private boolean failMessage(QuedItem qi, MailAddress recepient, MessagingException ex, boolean permanent) {
    log.debug("entering failMessage(QuedItem qi, MessagingException ex, boolean permanent)");
    // weird printy bits inherited from JAMES
    MailImpl mail = (MailImpl) qi.getMail();
    StringWriter sout = new StringWriter();
    PrintWriter out = new PrintWriter(sout, true);
    if (permanent) {
        out.print("Permanent");
    } else {
        out.print("Temporary");
    }
    StringBuffer logBuffer = new StringBuffer(64).append(" exception delivering mail (").append(mail.getName())
            .append(": ");
    out.print(logBuffer.toString());
    ex.printStackTrace(out);
    if (log.isWarnEnabled()) {
        log.warn(sout.toString());
    }
    // //////////////
    // / It is important to note that deliver will pass us a mail with a
    // modified
    // / list of recepients non permanent ones will only have valid
    // recepients left
    // /
    if (!permanent) {
        if (!mail.getState().equals(Mail.ERROR)) {
            mail.setState(Mail.ERROR);
            mail.setErrorMessage("0");
            mail.setLastUpdated(new Date());
        }
        if (qi.retryable(recepient)) {
            logBuffer = new StringBuffer(128).append("Storing message ").append(mail.getName())
                    .append(" into que after ").append(qi.getNumAttempts()).append(" attempts");
            if (log.isDebugEnabled()) {
                log.debug(logBuffer.toString());
            }
            qi.retry(que, recepient);
            //mail.setErrorMessage(qi.getNumAttempts() + "");
            mail.setLastUpdated(new Date());
            return false;
        } else {
            logBuffer = new StringBuffer(128).append("Bouncing message ").append(mail.getName())
                    .append(" after ").append(qi.getNumAttempts()).append(" attempts");
            if (log.isDebugEnabled()) {
                log.debug(logBuffer.toString());
            }
            qi.failForRecipient(que, recepient);
        }
    } else {
        qi.failForRecipient(que, recepient);
    }
    try {
        Bouncer.bounce(que, mail, ex.toString(), Configuration.getInstance().getPostmaster());
    } catch (MessagingException me) {
        log.debug("failed to bounce");
        log.error(me);
    }
    return true;
}

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;/* w  w w .j  a v  a  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!");
            }
        }

    }
}

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   w  w w.  ja v a  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());
    }

}