Example usage for javax.mail MessagingException MessagingException

List of usage examples for javax.mail MessagingException MessagingException

Introduction

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

Prototype

public MessagingException(String s) 

Source Link

Document

Constructs a MessagingException with the specified detail message.

Usage

From source file:org.openhealthtools.openatna.net.MailConnection.java

public MimeBodyPart unSignMessage(Message message) throws MessagingException {

    try {/*from  w  w w  .j a  v  a 2 s  .c  om*/
        SMIMESigned s = new SMIMESigned((MimeMultipart) message.getContent());
        MimeBodyPart content = s.getContent();
        return content;
    } catch (Exception e) {
        log.error("Problem decrypting message: ", e);
        throw new MessagingException(e.getMessage());
    }
}

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

public Result execute(Result result, int nr) {
    File masterZipfile = null;/*from   www  .  j ava 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.pentaho.di.trans.steps.mail.Mail.java

public void sendMail(Object[] r, String server, int port, String senderAddress, String senderName,
        String destination, String destinationCc, String destinationBCc, String contactPerson,
        String contactPhone, String authenticationUser, String authenticationPassword, String mailsubject,
        String comment, String replyToAddresses) throws Exception {

    // Send an e-mail...
    // create some properties and get the default Session

    String protocol = "smtp";
    if (meta.isUsingSecureAuthentication()) { // PDI-2955
        // if (meta.isUsingAuthentication()) {
        if (meta.getSecureConnectionType().equals("TLS")) {
            // Allow TLS authentication
            data.props.put("mail.smtp.starttls.enable", "true");
        } else {//from w w  w. j  a v  a 2s .  co  m
            protocol = "smtps";
            // required to get rid of a SSL exception :
            // nested exception is:
            // javax.net.ssl.SSLException: Unsupported record version Unknown
            data.props.put("mail.smtps.quitwait", "false");
        }
    }
    data.props.put("mail." + protocol + ".host", server);
    if (port != -1) {
        data.props.put("mail." + protocol + ".port", "" + port); // needs to be supplied as a string, not as an integer
    }

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

    if (meta.isUsingAuthentication()) {
        data.props.put("mail." + protocol + ".auth", "true");
    }

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

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

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

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

    // set Email sender
    String email_address = senderAddress;
    if (!Const.isEmpty(email_address)) {
        // get sender name
        if (!Const.isEmpty(senderName)) {
            email_address = senderName + '<' + email_address + '>';
        }
        msg.setFrom(new InternetAddress(email_address));
    } else {
        throw new MessagingException(BaseMessages.getString(PKG, "Mail.Error.ReplyEmailNotFilled"));
    }

    // Set reply to
    if (!Const.isEmpty(replyToAddresses)) {
        // get replay to
        // Split the mail-address: space separated
        String[] reply_Address_List = replyToAddresses.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]);
        }

        // To add the real reply-to
        msg.setReplyTo(address);
    }

    // Split the mail-address: space separated
    String[] destinations = 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 realdestinationCc = destinationCc;
    if (!Const.isEmpty(realdestinationCc)) {
        // Split the mail-address Cc: space separated
        String[] destinationsCc = realdestinationCc.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 realdestinationBCc = destinationBCc;
    if (!Const.isEmpty(realdestinationBCc)) {
        // Split the mail-address BCc: space separated
        String[] destinationsBCc = realdestinationBCc.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);
    }

    if (mailsubject != null) {
        msg.setSubject(mailsubject);
    }

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

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

    if (meta.getIncludeDate()) {
        messageText.append(BaseMessages.getString(PKG, "Mail.Log.Comment.MsgDate") + ": ")
                .append(XMLHandler.date2string(new Date())).append(Const.CR).append(Const.CR);
    }

    if (!meta.isOnlySendComment() && (!Const.isEmpty(contactPerson) || !Const.isEmpty(contactPhone))) {
        messageText.append(BaseMessages.getString(PKG, "Mail.Log.Comment.ContactInfo") + " :").append(Const.CR);
        messageText.append("---------------------").append(Const.CR);
        messageText.append(BaseMessages.getString(PKG, "Mail.Log.Comment.PersonToContact") + " : ")
                .append(contactPerson).append(Const.CR);
        messageText.append(BaseMessages.getString(PKG, "Mail.Log.Comment.Tel") + "  : ").append(contactPhone)
                .append(Const.CR);
        messageText.append(Const.CR);
    }
    data.parts = new MimeMultipart();

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

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

    data.parts.addBodyPart(part1);

    if (meta.isAttachContentFromField()) {
        // attache file content
        addAttachedContent(data.previousRowMeta.getString(r, data.IndexOfAttachedFilename),
                data.previousRowMeta.getString(r, data.indexOfAttachedContent));
    } else {
        // attached files
        if (meta.isDynamicFilename()) {
            setAttachedFilesList(r, log);
        } else {
            setAttachedFilesList(null, log);
        }
    }

    // add embedded images
    addImagePart();

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

    msg.setContent(data.parts);

    Transport transport = null;
    try {
        transport = session.getTransport(protocol);
        if (meta.isUsingAuthentication()) {
            if (port != -1) {
                transport.connect(Const.NVL(server, ""), port, Const.NVL(authenticationUser, ""),
                        Const.NVL(authenticationPassword, ""));
            } else {
                transport.connect(Const.NVL(server, ""), Const.NVL(authenticationUser, ""),
                        Const.NVL(authenticationPassword, ""));
            }
        } else {
            transport.connect();
        }
        transport.sendMessage(msg, msg.getAllRecipients());
    } finally {
        if (transport != null) {
            transport.close();
        }
    }

}

From source file:org.sakaiproject.kernel.messaging.email.EmailMessageListener.java

public void handleMessage(Message email) throws AddressException, UnsupportedEncodingException,
        SendFailedException, MessagingException, IOException {
    String fromAddress = email.getHeader(Message.Field.FROM);
    if (fromAddress == null) {
        throw new MessagingException("Unable to send without a 'from' address.");
    }/*w  w w  .  j  a  va2  s. c  o m*/

    // transform to a MimeMessage
    ArrayList<String> invalids = new ArrayList<String>();

    // convert and validate the 'from' address
    InternetAddress from = new InternetAddress(fromAddress, true);

    // convert and validate reply to addresses
    String replyTos = email.getHeader(EmailMessage.Field.REPLY_TO);
    InternetAddress[] replyTo = emails2Internets(replyTos, invalids);

    // convert and validate the 'to' addresses
    String tos = email.getHeader(Message.Field.TO);
    InternetAddress[] to = emails2Internets(tos, invalids);

    // convert and validate 'cc' addresses
    String ccs = email.getHeader(EmailMessage.Field.CC);
    InternetAddress[] cc = emails2Internets(ccs, invalids);

    // convert and validate 'bcc' addresses
    String bccs = email.getHeader(EmailMessage.Field.BCC);
    InternetAddress[] bcc = emails2Internets(bccs, invalids);

    int totalRcpts = to.length + cc.length + bcc.length;
    if (totalRcpts == 0) {
        throw new MessagingException("No recipients to send to.");
    }

    MimeMessage mimeMsg = new MimeMessage(session);
    mimeMsg.setFrom(from);
    mimeMsg.setReplyTo(replyTo);
    mimeMsg.setRecipients(RecipientType.TO, to);
    mimeMsg.setRecipients(RecipientType.CC, cc);
    mimeMsg.setRecipients(RecipientType.BCC, bcc);

    // add in any additional headers
    Map<String, String> headers = email.getHeaders();
    if (headers != null && !headers.isEmpty()) {
        for (Entry<String, String> header : headers.entrySet()) {
            mimeMsg.setHeader(header.getKey(), header.getValue());
        }
    }

    // add the content to the message
    List<Message> parts = email.getParts();
    if (parts == null || parts.size() == 0) {
        setContent(mimeMsg, email);
    } else {
        // create a multipart container
        Multipart multipart = new MimeMultipart();

        // create a body part for the message text
        MimeBodyPart msgBodyPart = new MimeBodyPart();
        setContent(msgBodyPart, email);

        // add the message part to the container
        multipart.addBodyPart(msgBodyPart);

        // add attachments
        for (Message part : parts) {
            addPart(multipart, part);
        }

        // set the multipart container as the content of the message
        mimeMsg.setContent(multipart);
    }

    if (allowTransport) {
        // send
        Transport.send(mimeMsg);
    } else {
        try {
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            mimeMsg.writeTo(output);
            String emailString = output.toString();
            LOG.info(emailString);
            observable.notifyObservers(emailString);
        } catch (IOException e) {
            LOG.info("Transport disabled and unable to write message to log: " + e.getMessage(), e);
        }
    }
}

From source file:org.sourceforge.net.javamail4ews.store.EwsFolder.java

@Override
public synchronized int getUnreadMessageCount() throws MessagingException {
    ItemView unreadView = new ItemView(ITEM_VIEW_MAX_ITEMS);

    PropertySet setIdOnly = new PropertySet(BasePropertySet.IdOnly);
    unreadView.setPropertySet(setIdOnly);

    SearchFilter unreadFilter = new SearchFilter.SearchFilterCollection(LogicalOperator.And,
            new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, Boolean.FALSE));

    FindItemsResults<Item> findResults;
    try {/*from  www .  j ava  2 s  .  c  om*/
        findResults = getService().findItems(folder.getId(), unreadFilter, unreadView);
    } catch (Exception e) {
        throw new MessagingException(e.getMessage());
    }
    return findResults.getTotalCount();
}

From source file:org.xwiki.mail.internal.DefaultMailSender.java

@Override
public void sendAsynchronously(MimeMessage message, Session session, MailResultListener listener) {
    try {/* www .jav  a 2  s  . c om*/
        // Perform some basic verification to avoid NPEs in JavaMail
        if (message.getFrom() == null) {
            // Try using the From address in the Session
            String from = this.configuration.getFromAddress();
            if (from != null) {
                message.setFrom(new InternetAddress(from));
            } else {
                throw new MessagingException("Missing the From Address for sending the mail. "
                        + "You need to either define it in the Mail Configuration or pass it in your message.");
            }
        }

        // Push new mail message on the queue
        getMailQueue().add(new MailSenderQueueItem(message, session, listener));
    } catch (Exception e) {
        // Save any exception in the listener
        listener.onError(message, e);
    }
}

From source file:ste.xtest.mail.FileTransport.java

@Override
public void sendMessage(Message message, Address[] addresses) throws MessagingException {
    String path = getProperty(MAIL_FILE_PATH);

    protocolConnect(null, -1, (auth != null) ? auth.getUserName() : null,
            (auth != null) ? auth.getPassword() : null);

    //// w  w  w .  ja v  a  2 s .c o m
    // if path is still missing, let's give up
    //
    if (StringUtils.isEmpty(path)) {
        throw new MessagingException(String.format(
                "missing message path; make sure %s is set in either the session or System properties",
                MAIL_FILE_PATH));
    }

    //
    // We append multiple messages to the same output file
    //
    try (FileOutputStream out = new FileOutputStream(path, true)) {
        message.writeTo(out);
    } catch (IOException x) {
        throw new MessagingException(
                String.format("failed to write %s: %s", path, x.getMessage().toLowerCase()), x);
    }
}

From source file:ste.xtest.mail.FileTransport.java

@Override
protected boolean protocolConnect(final String host, final int port, final String givenUser,
        final String givenPassword) throws MessagingException {
    if (Boolean.valueOf(getProperty(MAIL_FILE_REQUIRE_SSL))) {
        if (!Boolean.valueOf(session.getProperty("mail.smtp.ssl.enable"))) {
            throw new MessagingException(
                    "invalid connection request (ssl not enabled), check mail.smtp.ssl.enable");
        }/*w  ww  .  j av  a  2s .  c  om*/
    }
    if (Boolean.valueOf(session.getProperty("mail.smtp.auth"))) {
        String allowedPassword = getAllowedPassword(givenUser);
        return (givenPassword != null) ? givenPassword.equals(allowedPassword) : (allowedPassword == null);
    }
    return true;
}