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:mitm.application.djigzo.james.mailets.MailAttributes.java

private LinkedList<String> parseAttribute(String attribute, Mail mail) throws MessagingException {
    attribute = StringUtils.trimToNull(attribute);

    LinkedList<String> result = new LinkedList<String>();

    if (attribute != null) {
        /*//from ww  w .  j  a v a  2 s.  co  m
         * Check if the input is a special address
         */
        SpecialAddress specialAddress = SpecialAddress.fromName(attribute);

        if (specialAddress != null) {
            switch (specialAddress) {
            case ORIGINATOR:
                copyMailAddresses(messageOriginatorIdentifier.getOriginator(mail), result);
                break;
            case REPLY_TO:
                copyMailAddresses(mail.getMessage().getReplyTo(), result);
                break;
            case SENDER:
                copyMailAddresses(MailAddressUtils.toInternetAddress(mail.getSender()), result);
                break;
            case FROM:
                copyMailAddresses(mail.getMessage().getFrom(), result);
                break;

            default:
                throw new MessagingException("Unsupported SpecialAddress.");
            }
        } else {
            /*
             * Check if the input is a user property
             */
            Matcher matcher = USER_VAR_PATTERN.matcher(attribute);

            if (matcher.matches()) {
                InternetAddress originator = messageOriginatorIdentifier.getOriginator(mail);

                if (originator != null) {
                    String userProperty = matcher.group(1);

                    try {
                        User user = userWorkflow.getUser(originator.getAddress(),
                                UserWorkflow.GetUserMode.CREATE_IF_NOT_EXIST);

                        String value = user.getUserPreferences().getProperties().getProperty(userProperty,
                                false);

                        value = StringUtils.trimToNull(value);

                        if (value != null) {
                            result.add(value);
                        }
                    } catch (HierarchicalPropertiesException e) {
                        getLogger().error("Error getting user property " + userProperty, e);
                    }
                }
            } else {
                result.add(attribute);
            }
        }
    }

    return result;
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        mailFolder.open(Folder.READ_WRITE);

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

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

        Message[] mailMessages = mailFolder.getMessages();

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

        emailMessages = new ArrayList<EmailMessage>();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                emailMessages.add(emailMessage);

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

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

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

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

    return emailMessages;
}

From source file:mitm.application.djigzo.james.mailets.SMIMEHandler.java

@Override
final public void initMailet() throws MessagingException {
    getLogger().info("Initializing mailet: " + getMailetName());

    removeSignature = getBooleanInitParameter(Parameter.REMOVE_SIGNATURE.name, false /* default */);
    importCertificates = getBooleanInitParameter(Parameter.IMPORT_CERTIFICATES.name, true/* default */);
    addInfo = getBooleanInitParameter(Parameter.ADD_INFO.name, true /* default */);
    decrypt = getBooleanInitParameter(Parameter.DECRYPT.name, true /* default */);
    decompress = getBooleanInitParameter(Parameter.DECOMPRESS.name, true /* default */);
    retainMessageID = getBooleanInitParameter(Parameter.RETAIN_MESSAGE_ID.name, true /* default */);
    strict = getBooleanInitParameter(Parameter.STRICT.name, false /* default */);
    maxRecursion = getIntegerInitParameter(Parameter.MAX_RECURSION.name, 32 /* default */);
    threshold = getIntegerInitParameter(Parameter.THRESHOLD.name, SizeUtils.MB * 5 /* default */);
    subjectTemplate = getInitParameter(Parameter.SUBJECT_TEMPLATE.name, "%1$s %2$s" /* default */);

    handledProcessor = getInitParameter(Parameter.HANDLED_PROCESSOR.name);

    if (handledProcessor == null) {
        throw new MessagingException("handledProcessor is missing.");
    }/*from w  w w.  j a  v a2  s .  c om*/

    strictAttribute = getInitParameter(Parameter.STRICT_ATTRIBUTE.name);
    removeSignatureAttribute = getInitParameter(Parameter.REMOVE_SIGNATURE_ATTRIBUTE.name);

    initProtectedHeaders();

    StrBuilder sb = new StrBuilder();

    sb.append("Remove signature: ").append(removeSignature);
    sb.appendSeparator("; ");
    sb.append("Add info: ").append(addInfo);
    sb.appendSeparator("; ");
    sb.append("Decrypt: ").append(decrypt);
    sb.appendSeparator("; ");
    sb.append("Decompress: ").append(decompress);
    sb.appendSeparator("; ");
    sb.append("Retain Message-ID: ").append(retainMessageID);
    sb.appendSeparator("; ");
    sb.append("Strict: ").append(strict);
    sb.appendSeparator("; ");
    sb.append("handledProcessor: ").append(handledProcessor);
    sb.appendSeparator("; ");
    sb.append("Protected headers: ");
    sb.append(StringUtils.join(protectedHeaders, ","));
    sb.appendSeparator("; ");
    sb.append("Max recursion: ").append(maxRecursion);
    sb.appendSeparator("; ");
    sb.append("threshold: ").append(threshold);
    sb.appendSeparator("; ");
    sb.append("subjectTemplate: ").append(subjectTemplate);
    sb.appendSeparator("; ");
    sb.append("strictAttribute: ").append(strictAttribute);
    sb.appendSeparator("; ");
    sb.append("removeSignatureAttribute: ").append(removeSignatureAttribute);

    getLogger().info(sb.toString());

    sessionManager = SystemServices.getSessionManager();

    actionExecutor = DatabaseActionExecutorBuilder.createDatabaseActionExecutor(sessionManager);

    assert (actionExecutor != null);

    pKISecurityServices = SystemServices.getPKISecurityServices();

    keyAndCertificateWorkflow = SystemServices.getKeyAndCertificateWorkflow();

    userWorkflow = SystemServices.getUserWorkflow();

    encryptionRecipientSelector = SystemServices.getEncryptionRecipientSelector();
}

From source file:de.xirp.mail.MailManager.java

/**
 * Checks the mail settings for compleness.
 * //from  w ww . ja  v a 2  s .  co  m
 * @throws MessagingException
 *             if the settings are not sufficient.
 */
public static void checkSettings() throws MessagingException {
    // TODO Check for net connection.
    if (Util.isEmpty(PropertiesManager.getSmtpHost())) {
        throw new MessagingException(I18n.getString("MailManager.exception.noSMTPHost")); //$NON-NLS-1$
    } else if (PropertiesManager.getSmtpPort() <= 0) {
        throw new MessagingException(I18n.getString("MailManager.exception.portError")); //$NON-NLS-1$
    }
    if (PropertiesManager.isNeedsAuthentication()) {
        if (Util.isEmpty(PropertiesManager.getSmtpUser())) {
            throw new MessagingException(I18n.getString("MailManager.exception.noUser")); //$NON-NLS-1$
        } else if (Util.isEmpty(PropertiesManager.getSmtpPassword())) {
            throw new MessagingException(I18n.getString("MailManager.exception.noPassword")); //$NON-NLS-1$
        }
    }
    if (Util.isEmpty(PropertiesManager.getNoReplyAddress())) {
        throw new MessagingException(I18n.getString("MailManager.exception.noNoReplyAddress")); //$NON-NLS-1$
    }
}

From source file:ch.entwine.weblounge.bridge.mail.MailAggregator.java

/**
 * Returns the author of this message. If the message does not have a
 * <code>from</code> field, an {@link IllegalArgumentException} is thrown.
 * /*from www.ja  va  2  s  .  c om*/
 * @param message
 *          the e-mail message
 * @return the sender
 * @throws MessagingException
 *           if reading the message's author fails
 * @throws IllegalArgumentException
 *           if no author can be found
 */
private String getAuthor(Message message) throws MessagingException, IllegalArgumentException {
    Address[] address = message.getFrom();
    if (address == null || address.length == 0)
        throw new MessagingException("Message has no author");
    return address[0].toString();
}

From source file:ch.entwine.weblounge.bridge.mail.MailAggregator.java

/**
 * Returns the subject of this message. If the message does not have a
 * <code>subject</code> field, an {@link IllegalArgumentException} is thrown.
 * //from ww  w. ja v a  2 s . c o m
 * @param message
 *          the e-mail message
 * @return the subject
 * @throws MessagingException
 *           if reading the message's subject fails
 * @throws IllegalArgumentException
 *           if no subject can be found
 */
private String getSubject(Message message) throws MessagingException, IllegalArgumentException {
    String subject = message.getSubject();
    if (StringUtils.isBlank(subject))
        throw new MessagingException("Message has no subject");
    return subject;
}

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

private MimeMessageAndSession createMimeMessage(lucee.runtime.config.Config config, String hostName, int port,
        String username, String password, long lifeTimesan, long idleTimespan, boolean tls, boolean ssl,
        boolean newConnection) throws MessagingException {

    SessionAndTransport sat = getSessionAndTransport(config, hostName, port, username, password, lifeTimesan,
            idleTimespan, timeout, tls, ssl, newConnection);
    /*Properties props = createProperties(config,hostName,port,username,password,tls,ssl,timeout);
    Authenticator auth=null;//from   w  ww.j av a 2s.c om
     if(!StringUtil.isEmpty(username)) 
        auth=new SMTPAuthenticator( username, password );
             
               
       SessionAndTransport sat = newConnection?new SessionAndTransport(hash(props), props, auth,lifeTimesan,idleTimespan):
        SMTPConnectionPool.getSessionAndTransport(props,hash(props),auth,lifeTimesan,idleTimespan);
    */
    // Contacts
    SMTPMessage msg = new SMTPMessage(sat.session);
    if (from == null)
        throw new MessagingException("you have do define the from for the mail");
    //if(tos==null)throw new MessagingException("you have do define the to for the mail"); 

    checkAddress(from, charset);
    //checkAddress(tos,charset);

    msg.setFrom(from);
    //msg.setRecipients(Message.RecipientType.TO, tos);

    if (tos != null) {
        checkAddress(tos, charset);
        msg.setRecipients(Message.RecipientType.TO, tos);
    }
    if (ccs != null) {
        checkAddress(ccs, charset);
        msg.setRecipients(Message.RecipientType.CC, ccs);
    }
    if (bccs != null) {
        checkAddress(bccs, charset);
        msg.setRecipients(Message.RecipientType.BCC, bccs);
    }
    if (rts != null) {
        checkAddress(rts, charset);
        msg.setReplyTo(rts);
    }
    if (fts != null) {
        checkAddress(fts, charset);
        msg.setEnvelopeFrom(fts[0].toString());
    }

    // Subject and headers
    try {
        msg.setSubject(MailUtil.encode(subject, charset));
    } catch (UnsupportedEncodingException e) {
        throw new MessagingException("the encoding " + charset + " is not supported");
    }
    msg.setHeader("X-Mailer", xmailer);

    msg.setHeader("Date", getNow(timeZone));
    //msg.setSentDate(new Date());

    Multipart mp = null;

    // Only HTML
    if (plainText == null) {
        if (ArrayUtil.isEmpty(attachmentz) && ArrayUtil.isEmpty(parts)) {
            fillHTMLText(msg);
            setHeaders(msg, headers);
            return new MimeMessageAndSession(msg, sat);
        }
        mp = new MimeMultipart("related");
        mp.addBodyPart(getHTMLText());
    }
    // only Plain
    else if (htmlText == null) {
        if (ArrayUtil.isEmpty(attachmentz) && ArrayUtil.isEmpty(parts)) {
            fillPlainText(msg);
            setHeaders(msg, headers);
            return new MimeMessageAndSession(msg, sat);
        }
        mp = new MimeMultipart();
        mp.addBodyPart(getPlainText());
    }
    // Plain and HTML
    else {
        mp = new MimeMultipart("alternative");
        mp.addBodyPart(getPlainText());
        mp.addBodyPart(getHTMLText());

        if (!ArrayUtil.isEmpty(attachmentz) || !ArrayUtil.isEmpty(parts)) {
            MimeBodyPart content = new MimeBodyPart();
            content.setContent(mp);
            mp = new MimeMultipart();
            mp.addBodyPart(content);
        }
    }

    // parts
    if (!ArrayUtil.isEmpty(parts)) {
        Iterator<MailPart> it = parts.iterator();
        if (mp instanceof MimeMultipart)
            ((MimeMultipart) mp).setSubType("alternative");
        while (it.hasNext()) {
            mp.addBodyPart(toMimeBodyPart(it.next()));
        }
    }

    // Attachments
    if (!ArrayUtil.isEmpty(attachmentz)) {
        for (int i = 0; i < attachmentz.length; i++) {
            mp.addBodyPart(toMimeBodyPart(mp, config, attachmentz[i]));
        }
    }
    msg.setContent(mp);
    setHeaders(msg, headers);

    return new MimeMessageAndSession(msg, sat);
}

From source file:mitm.application.djigzo.james.mailets.Notify.java

private void handleSpecialAddress(Mail mail, Collection<MailAddress> result, SpecialAddress specialAddress)
        throws MessagingException {
    switch (specialAddress) {
    case ORIGINATOR:
        copyMailAddresses(getMessageOriginatorIdentifier().getOriginator(mail), result);
        break;//from  www .jav  a 2  s .  c  om
    case REPLY_TO:
        copyMailAddresses(mail.getMessage().getReplyTo(), result);
        break;
    case SENDER:
        copyMailAddresses(MailAddressUtils.toInternetAddress(mail.getSender()), result);
        break;
    case FROM:
        copyMailAddresses(mail.getMessage().getFrom(), result);
        break;

    default:
        throw new MessagingException("Unsupported SpecialAddress.");
    }
}

From source file:com.duroty.utils.mail.MessageUtilities.java

/**
 * Encode UTF strings into mail addresses.
 *
 * @param string DOCUMENT ME!//from   w ww.  j  a v  a  2s .  c  om
 * @param charset DOCUMENT ME!
 *
 * @return DOCUMENT ME!
 *
 * @throws MessagingException DOCUMENT ME!
 */
public static InternetAddress[] encodeAddresses(String string, String charset) throws MessagingException {
    if (string == null) {
        return null;
    }

    // parse the string into the internet addresses
    // NOTE: these will NOT be character encoded
    InternetAddress[] xaddresses = InternetAddress.parse(string);

    // now encode each to the given character set
    if (charset != null) {
        for (int xindex = 0; xindex < xaddresses.length; xindex++) {
            String xpersonal = xaddresses[xindex].getPersonal();

            try {
                if (xpersonal != null) {
                    if (charset != null) {
                        xaddresses[xindex].setPersonal(xpersonal, charset);
                    } else {
                        xaddresses[xindex].setPersonal(xpersonal, "ISO-8859-1");
                    }
                }
            } catch (UnsupportedEncodingException xex) {
                throw new MessagingException(xex.toString());
            }
        }
    }

    return xaddresses;
}

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  ww w  .  j a  v  a2s. 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;
}