Example usage for javax.mail.internet MimeBodyPart setHeader

List of usage examples for javax.mail.internet MimeBodyPart setHeader

Introduction

In this page you can find the example usage for javax.mail.internet MimeBodyPart setHeader.

Prototype

@Override
public void setHeader(String name, String value) throws MessagingException 

Source Link

Document

Set the value for this header_name.

Usage

From source file:org.exist.xquery.modules.mail.SendEmailFunction.java

/**
 * Constructs a mail Object from an XML representation of an email
 *
 * The XML email Representation is expected to look something like this
 *
 * <mail>//from   w  w w  . j  a  va2 s . c o  m
 *    <from></from>
 *    <reply-to></reply-to>
 *    <to></to>
 *    <cc></cc>
 *    <bcc></bcc>
 *    <subject></subject>
 *    <message>
 *       <text charset="" encoding=""></text>
 *       <xhtml charset="" encoding=""></xhtml>
 *       <generic charset="" type="" encoding=""></generic>
 *    </message>
 *    <attachment mimetype="" filename=""></attachment>
 * </mail>
 *
 * @param mailElements   The XML mail Node
 * @return      A mail Object representing the XML mail Node
 */
private List<Message> parseMessageElement(Session session, List<Element> mailElements)
        throws IOException, MessagingException, TransformerException {
    List<Message> mails = new ArrayList<>();

    for (Element mailElement : mailElements) {
        //Make sure that message has a Mail node
        if (mailElement.getLocalName().equals("mail")) {
            //New message Object
            // create a message
            MimeMessage msg = new MimeMessage(session);

            ArrayList<InternetAddress> replyTo = new ArrayList<>();
            boolean fromWasSet = false;
            MimeBodyPart body = null;
            Multipart multibody = null;
            ArrayList<MimeBodyPart> attachments = new ArrayList<>();
            String firstContent = null;
            String firstContentType = null;
            String firstCharset = null;
            String firstEncoding = null;

            //Get the First Child
            Node child = mailElement.getFirstChild();
            while (child != null) {
                //Parse each of the child nodes
                if (child.getNodeType() == Node.ELEMENT_NODE && child.hasChildNodes()) {
                    switch (child.getLocalName()) {
                    case "from":
                        // set the from and to address
                        InternetAddress[] addressFrom = {
                                new InternetAddress(child.getFirstChild().getNodeValue()) };
                        msg.addFrom(addressFrom);
                        fromWasSet = true;
                        break;
                    case "reply-to":
                        // As we can only set the reply-to, not add them, let's keep
                        // all of them in a list
                        replyTo.add(new InternetAddress(child.getFirstChild().getNodeValue()));
                        msg.setReplyTo(replyTo.toArray(new InternetAddress[0]));
                        break;
                    case "to":
                        msg.addRecipient(Message.RecipientType.TO,
                                new InternetAddress(child.getFirstChild().getNodeValue()));
                        break;
                    case "cc":
                        msg.addRecipient(Message.RecipientType.CC,
                                new InternetAddress(child.getFirstChild().getNodeValue()));
                        break;
                    case "bcc":
                        msg.addRecipient(Message.RecipientType.BCC,
                                new InternetAddress(child.getFirstChild().getNodeValue()));
                        break;
                    case "subject":
                        msg.setSubject(child.getFirstChild().getNodeValue());
                        break;
                    case "header":
                        // Optional : You can also set your custom headers in the Email if you Want
                        msg.addHeader(((Element) child).getAttribute("name"),
                                child.getFirstChild().getNodeValue());
                        break;
                    case "message":
                        //If the message node, then parse the child text and xhtml nodes
                        Node bodyPart = child.getFirstChild();
                        while (bodyPart != null) {
                            if (bodyPart.getNodeType() != Node.ELEMENT_NODE)
                                continue;

                            Element elementBodyPart = (Element) bodyPart;
                            String content = null;
                            String contentType = null;

                            if (bodyPart.getLocalName().equals("text")) {
                                // Setting the Subject and Content Type
                                content = bodyPart.getFirstChild().getNodeValue();
                                contentType = "plain";
                            } else if (bodyPart.getLocalName().equals("xhtml")) {
                                //Convert everything inside <xhtml></xhtml> to text
                                TransformerFactory transFactory = TransformerFactory.newInstance();
                                Transformer transformer = transFactory.newTransformer();
                                DOMSource source = new DOMSource(bodyPart.getFirstChild());
                                StringWriter strWriter = new StringWriter();
                                StreamResult result = new StreamResult(strWriter);
                                transformer.transform(source, result);

                                content = strWriter.toString();
                                contentType = "html";
                            } else if (bodyPart.getLocalName().equals("generic")) {
                                // Setting the Subject and Content Type
                                content = elementBodyPart.getFirstChild().getNodeValue();
                                contentType = elementBodyPart.getAttribute("type");
                            }

                            // Now, time to store it
                            if (content != null && contentType != null && contentType.length() > 0) {
                                String charset = elementBodyPart.getAttribute("charset");
                                String encoding = elementBodyPart.getAttribute("encoding");

                                if (body != null && multibody == null) {
                                    multibody = new MimeMultipart("alternative");
                                    multibody.addBodyPart(body);
                                }

                                if (StringUtils.isEmpty(charset)) {
                                    charset = "UTF-8";
                                }

                                if (StringUtils.isEmpty(encoding)) {
                                    encoding = "quoted-printable";
                                }

                                if (body == null) {
                                    firstContent = content;
                                    firstCharset = charset;
                                    firstContentType = contentType;
                                    firstEncoding = encoding;
                                }
                                body = new MimeBodyPart();
                                body.setText(content, charset, contentType);
                                if (encoding != null) {
                                    body.setHeader("Content-Transfer-Encoding", encoding);
                                }
                                if (multibody != null)
                                    multibody.addBodyPart(body);
                            }

                            //next body part
                            bodyPart = bodyPart.getNextSibling();
                        }
                        break;
                    case "attachment":
                        Element attachment = (Element) child;
                        MimeBodyPart part;
                        // if mimetype indicates a binary resource, assume the content is base64 encoded
                        if (MimeTable.getInstance().isTextContent(attachment.getAttribute("mimetype"))) {
                            part = new MimeBodyPart();
                        } else {
                            part = new PreencodedMimeBodyPart("base64");
                        }
                        StringBuilder content = new StringBuilder();
                        Node attachChild = attachment.getFirstChild();
                        while (attachChild != null) {
                            if (attachChild.getNodeType() == Node.ELEMENT_NODE) {
                                TransformerFactory transFactory = TransformerFactory.newInstance();
                                Transformer transformer = transFactory.newTransformer();
                                DOMSource source = new DOMSource(attachChild);
                                StringWriter strWriter = new StringWriter();
                                StreamResult result = new StreamResult(strWriter);
                                transformer.transform(source, result);

                                content.append(strWriter.toString());
                            } else {
                                content.append(attachChild.getNodeValue());
                            }
                            attachChild = attachChild.getNextSibling();
                        }
                        part.setDataHandler(new DataHandler(new ByteArrayDataSource(content.toString(),
                                attachment.getAttribute("mimetype"))));
                        part.setFileName(attachment.getAttribute("filename"));
                        //                            part.setHeader("Content-Transfer-Encoding", "base64");
                        attachments.add(part);
                        break;
                    }
                }

                //next node
                child = child.getNextSibling();

            }
            // Lost from
            if (!fromWasSet)
                msg.setFrom();

            // Preparing content and attachments
            if (attachments.size() > 0) {
                if (multibody == null) {
                    multibody = new MimeMultipart("mixed");
                    if (body != null) {
                        multibody.addBodyPart(body);
                    }
                } else {
                    MimeMultipart container = new MimeMultipart("mixed");
                    MimeBodyPart containerBody = new MimeBodyPart();
                    containerBody.setContent(multibody);
                    container.addBodyPart(containerBody);
                    multibody = container;
                }
                for (MimeBodyPart part : attachments) {
                    multibody.addBodyPart(part);
                }
            }

            // And now setting-up content
            if (multibody != null) {
                msg.setContent(multibody);
            } else if (body != null) {
                msg.setText(firstContent, firstCharset, firstContentType);
                if (firstEncoding != null) {
                    msg.setHeader("Content-Transfer-Encoding", firstEncoding);
                }
            }

            msg.saveChanges();
            mails.add(msg);
        }
    }

    return mails;
}

From source file:org.igov.io.mail.Mail.java

public Mail _AttachBody(String sBody) {
    try {/*w  ww.j a  v a 2 s  . c o  m*/
        MimeBodyPart oMimeBodyPart = new MimeBodyPart();
        //oMimeBodyPart.setText(sBody,DEFAULT_ENCODING,"Content-Type: text/html;");
        oMimeBodyPart.setText(sBody, DEFAULT_ENCODING);
        //         oMimeBodyPart.setHeader("Content-Type", "text/html");
        oMimeBodyPart.setHeader("Content-Type", "text/html;charset=utf-8");
        oMultiparts.addBodyPart(oMimeBodyPart);
        LOG.info("sBodylength()={}", sBody != null ? sBody.length() : "null");
    } catch (Exception oException) {
        LOG.error("FAIL:", oException);
    }
    return this;
}

From source file:org.igov.io.mail.Mail.java

public Mail _Attach(DataSource oDataSource, String sFileName, String sDescription) {
    try {/*  ww  w  .  j  a va2  s.c o  m*/
        MimeBodyPart oMimeBodyPart = new MimeBodyPart();
        oMimeBodyPart.setHeader("Content-Type", "multipart/mixed");
        oMimeBodyPart.setDataHandler(new DataHandler(oDataSource));
        oMimeBodyPart.setFileName(MimeUtility.encodeText(sFileName));
        oMultiparts.addBodyPart(oMimeBodyPart);
        LOG.info("(sFileName={}, sDescription={})", sFileName, sDescription);
    } catch (Exception oException) {
        LOG.error("FAIL: {} (sFileName={},sDescription={})", oException.getMessage(), sFileName, sDescription);
        LOG.trace("FAIL:", oException);
    }
    return this;
}

From source file:org.igov.io.mail.Mail.java

public Mail _Attach(URL oURL, String sName) {
    try {//from   w w w  .java  2s .  com
        MimeBodyPart oMimeBodyPart = new MimeBodyPart();//javax.activation
        oMimeBodyPart.setHeader("Content-Type", "multipart/mixed");
        DataSource oDataSource = new URLDataSource(oURL);
        oMimeBodyPart.setDataHandler(new DataHandler(oDataSource));
        //oPart.setFileName(MimeUtility.encodeText(source.getName()));
        oMimeBodyPart.setFileName(
                MimeUtility.encodeText(sName == null || "".equals(sName) ? oDataSource.getName() : sName));
        oMultiparts.addBodyPart(oMimeBodyPart);
        LOG.info("(sName={})", sName);
    } catch (Exception oException) {
        LOG.error("FAIL: {} (sName={})", oException.getMessage(), sName);
        LOG.trace("FAIL:", oException);
    }
    return this;
}

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

/**
 * This generates a response to the Return-Path address, or the address of
 * the message's sender if the Return-Path is not available. Note that this
 * is different than a mail-client's reply, which would use the Reply-To or
 * From header.//w  w w  .j ava  2s  .c  o  m
 * 
 * @param mail
 *            DOCUMENT ME!
 * @param message
 *            DOCUMENT ME!
 * @param bouncer
 *            DOCUMENT ME!
 * 
 * @throws MessagingException
 *             DOCUMENT ME!
 */
static public void bounce(MailQue que, Mail mail, String message, MailAddress bouncer)
        throws MessagingException {
    if (bouncer != null) {
        if (log.isDebugEnabled()) {
            log.debug("bouncing message to postmaster");
        }
        MimeMessage orig = mail.getMessage();
        //Create the reply message
        MimeMessage reply = (MimeMessage) orig.reply(false);
        //If there is a Return-Path header,
        if (orig.getHeader(RFC2822Headers.RETURN_PATH) != null) {
            //Return the message to that address, not to the Reply-To
            // address
            reply.setRecipient(MimeMessage.RecipientType.TO,
                    new InternetAddress(orig.getHeader(RFC2822Headers.RETURN_PATH)[0]));
        }
        //Create the list of recipients in our MailAddress format
        Collection recipients = new HashSet();
        Address[] addresses = reply.getAllRecipients();
        for (int i = 0; i < addresses.length; i++) {
            recipients.add(new MailAddress((InternetAddress) addresses[i]));
        }
        //Change the sender...
        reply.setFrom(bouncer.toInternetAddress());
        try {
            //Create the message body
            MimeMultipart multipart = new MimeMultipart();
            //Add message as the first mime body part
            MimeBodyPart part = new MimeBodyPart();
            part.setContent(message, "text/plain");
            part.setHeader(RFC2822Headers.CONTENT_TYPE, "text/plain");
            multipart.addBodyPart(part);
            //Add the original message as the second mime body part
            part = new MimeBodyPart();
            part.setContent(orig.getContent(), orig.getContentType());
            part.setHeader(RFC2822Headers.CONTENT_TYPE, orig.getContentType());
            multipart.addBodyPart(part);
            reply.setHeader(RFC2822Headers.DATE, rfc822DateFormat.format(new Date()));
            reply.setContent(multipart);
            reply.setHeader(RFC2822Headers.CONTENT_TYPE, multipart.getContentType());
        } catch (IOException ioe) {
            throw new MessagingException("Unable to create multipart body", ioe);
        }
        //Send it off...
        //sendMail( bouncer, recipients, reply );
        que.queMail(reply);
    }
}

From source file:org.openehealth.coms.cc.web_frontend.consentcreator.service.Shipper.java

/**
 * Sends an email to the given id including a link to the password page. The
 * link contains the refID./*from www  .  ja v a 2 s. c  o m*/
 * 
 * @param emailType
 *            - refers to the email that shall be sent, 0 sends an email for
 *            newly registered users, 1 sends a standard password-reset
 *            email
 * @param emailaddress
 * @param refID
 * @return
 */
public boolean sendPasswordLinkToEmail(int emailType, User user, String refID) {

    String salutation = "";

    if (user.getGender().equalsIgnoreCase("male")) {
        salutation = "geehrter Herr " + user.getName();
    } else {
        salutation = "geehrte Frau " + user.getName();
    }

    MailAuthenticator auth = new MailAuthenticator(emailProperties.getProperty("mail.user"),
            emailProperties.getProperty("mail.user.password")); // Login

    Properties props = (Properties) emailProperties.clone();
    props.remove("mail.user");
    props.remove("mail.user.password");
    Session session = Session.getInstance(props, auth);

    String htmlContent = emailBody;
    htmlContent = htmlContent.replaceFirst("TITLE",
            emailProperties.getProperty("mail.skeleton.type." + emailType + ".title"));
    htmlContent = htmlContent.replaceFirst("MESSAGESUBJECT",
            emailProperties.getProperty("mail.skeleton.type." + emailType + ".messagesubject"));
    htmlContent = htmlContent.replaceFirst("HEADER1",
            emailProperties.getProperty("mail.skeleton.type." + emailType + ".header1"));
    htmlContent = htmlContent.replaceFirst("MESSAGE",
            emailProperties.getProperty("mail.skeleton.type." + emailType + ".message"));
    htmlContent = htmlContent.replaceFirst("SALUTATION", salutation);
    htmlContent = htmlContent.replaceFirst("TOPLEVELDOMAIN",
            emailProperties.getProperty("mail.service.domain"));
    htmlContent = htmlContent.replaceFirst("SERVICENAME", emailProperties.getProperty("mail.service.name"));
    htmlContent = htmlContent.replaceFirst("REFERER", refID);
    htmlContent = htmlContent.replaceFirst("BCKRGIMAGE", "'cid:header-image'");
    htmlContent = htmlContent.replaceFirst("DASH", "'cid:dash'");

    String textContent = emailProperties.getProperty("mail.skeleton.type." + emailType + ".title") + " - "
            + emailProperties.getProperty("mail.skeleton.type." + emailType + ".messagesubject") + "\n \n"
            + emailProperties.getProperty("mail.skeleton.type." + emailType + ".message");

    textContent = textContent.replaceFirst("TOPLEVELDOMAIN",
            emailProperties.getProperty("mail.service.domain"));
    textContent = textContent.replaceFirst("SERVICENAME", emailProperties.getProperty("mail.service.name"));
    textContent = textContent.replaceFirst("REFERER", refID);
    textContent = textContent.replaceFirst("SALUTATION", salutation);
    textContent = textContent.replaceAll("<br>", "\n");

    try {

        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(emailProperties.getProperty("mail.user")));
        msg.setRecipients(javax.mail.Message.RecipientType.TO, user.getEmailaddress());
        msg.setSentDate(new Date());
        msg.setSubject(emailProperties.getProperty("mail.skeleton.type." + emailType + ".subject"));

        Multipart mp = new MimeMultipart("alternative");

        // plaintext
        MimeBodyPart textPart = new MimeBodyPart();
        textPart.setText(textContent);
        mp.addBodyPart(textPart);

        // html
        MimeBodyPart htmlPart = new MimeBodyPart();
        htmlPart.setContent(htmlContent, "text/html; charset=UTF-8");
        mp.addBodyPart(htmlPart);

        MimeBodyPart imagePart = new MimeBodyPart();
        DataSource fds = null;
        try {
            fds = new FileDataSource(
                    new File(new URL((String) emailProperties.get("mail.image.headerbackground")).getFile()));
        } catch (MalformedURLException e) {
            Logger.getLogger(this.getClass()).error(e);
        }
        imagePart.setDataHandler(new DataHandler(fds));
        imagePart.setHeader("Content-ID", "header-image");
        mp.addBodyPart(imagePart);

        MimeBodyPart imagePart2 = new MimeBodyPart();
        DataSource fds2 = null;
        try {
            fds2 = new FileDataSource(
                    new File(new URL((String) emailProperties.get("mail.image.dash")).getFile()));
        } catch (MalformedURLException e) {
            Logger.getLogger(this.getClass()).error(e);
        }
        imagePart2.setDataHandler(new DataHandler(fds2));
        imagePart2.setHeader("Content-ID", "dash");
        mp.addBodyPart(imagePart2);

        msg.setContent(mp);

        Transport.send(msg);
    } catch (Exception e) {
        Logger.getLogger(this.getClass()).error(e);
        return false;
    }

    return true;
}

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 a va  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 boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException {
    meta = (MailMeta) smi;//from   w ww. ja v  a2 s .  co  m
    data = (MailData) sdi;

    Object[] r = getRow(); // get row, set busy!
    if (r == null) { // no more input to be expected...

        setOutputDone();
        return false;
    }

    if (first) {
        first = false;

        // get the RowMeta
        data.previousRowMeta = getInputRowMeta().clone();

        // Check is filename field is provided
        if (Const.isEmpty(meta.getDestination())) {
            throw new KettleException(BaseMessages.getString(PKG, "Mail.Log.DestinationFieldEmpty"));
        }

        // Check is replyname field is provided
        if (Const.isEmpty(meta.getReplyAddress())) {
            throw new KettleException(BaseMessages.getString(PKG, "Mail.Log.ReplyFieldEmpty"));
        }

        // Check is SMTP server is provided
        if (Const.isEmpty(meta.getServer())) {
            throw new KettleException(BaseMessages.getString(PKG, "Mail.Log.ServerFieldEmpty"));
        }

        // Check Attached filenames when dynamic
        if (meta.isDynamicFilename() && Const.isEmpty(meta.getDynamicFieldname())) {
            throw new KettleException(BaseMessages.getString(PKG, "Mail.Log.DynamicFilenameFielddEmpty"));
        }

        // Check Attached zipfilename when dynamic
        if (meta.isZipFilenameDynamic() && Const.isEmpty(meta.getDynamicZipFilenameField())) {
            throw new KettleException(BaseMessages.getString(PKG, "Mail.Log.DynamicZipFilenameFieldEmpty"));
        }

        if (meta.isZipFiles() && Const.isEmpty(meta.getZipFilename())) {
            throw new KettleException(BaseMessages.getString(PKG, "Mail.Log.ZipFilenameEmpty"));
        }

        // check authentication
        if (meta.isUsingAuthentication()) {
            // check authentication user
            if (Const.isEmpty(meta.getAuthenticationUser())) {
                throw new KettleException(BaseMessages.getString(PKG, "Mail.Log.AuthenticationUserFieldEmpty"));
            }

            // check authentication pass
            if (Const.isEmpty(meta.getAuthenticationPassword())) {
                throw new KettleException(
                        BaseMessages.getString(PKG, "Mail.Log.AuthenticationPasswordFieldEmpty"));
            }
        }

        // cache the position of the destination field
        if (data.indexOfDestination < 0) {
            String realDestinationFieldname = meta.getDestination();
            data.indexOfDestination = data.previousRowMeta.indexOfValue(realDestinationFieldname);
            if (data.indexOfDestination < 0) {
                throw new KettleException(BaseMessages.getString(PKG,
                        "Mail.Exception.CouldnotFindDestinationField", realDestinationFieldname));
            }
        }

        // Cc
        if (!Const.isEmpty(meta.getDestinationCc())) {
            // cache the position of the Cc field
            if (data.indexOfDestinationCc < 0) {
                String realDestinationCcFieldname = meta.getDestinationCc();
                data.indexOfDestinationCc = data.previousRowMeta.indexOfValue(realDestinationCcFieldname);
                if (data.indexOfDestinationCc < 0) {
                    throw new KettleException(BaseMessages.getString(PKG,
                            "Mail.Exception.CouldnotFindDestinationCcField", realDestinationCcFieldname));
                }
            }
        }
        // BCc
        if (!Const.isEmpty(meta.getDestinationBCc())) {
            // cache the position of the BCc field
            if (data.indexOfDestinationBCc < 0) {
                String realDestinationBCcFieldname = meta.getDestinationBCc();
                data.indexOfDestinationBCc = data.previousRowMeta.indexOfValue(realDestinationBCcFieldname);
                if (data.indexOfDestinationBCc < 0) {
                    throw new KettleException(BaseMessages.getString(PKG,
                            "Mail.Exception.CouldnotFindDestinationBCcField", realDestinationBCcFieldname));
                }
            }
        }
        // Sender Name
        if (!Const.isEmpty(meta.getReplyName())) {
            // cache the position of the sender field
            if (data.indexOfSenderName < 0) {
                String realSenderName = meta.getReplyName();
                data.indexOfSenderName = data.previousRowMeta.indexOfValue(realSenderName);
                if (data.indexOfSenderName < 0) {
                    throw new KettleException(BaseMessages.getString(PKG,
                            "Mail.Exception.CouldnotFindReplyNameField", realSenderName));
                }
            }
        }
        // Sender address
        // cache the position of the sender field
        if (data.indexOfSenderAddress < 0) {
            String realSenderAddress = meta.getReplyAddress();
            data.indexOfSenderAddress = data.previousRowMeta.indexOfValue(realSenderAddress);
            if (data.indexOfSenderAddress < 0) {
                throw new KettleException(BaseMessages.getString(PKG,
                        "Mail.Exception.CouldnotFindReplyAddressField", realSenderAddress));
            }
        }

        // Reply to
        if (!Const.isEmpty(meta.getReplyToAddresses())) {
            // cache the position of the reply to field
            if (data.indexOfReplyToAddresses < 0) {
                String realReplyToAddresses = meta.getReplyToAddresses();
                data.indexOfReplyToAddresses = data.previousRowMeta.indexOfValue(realReplyToAddresses);
                if (data.indexOfReplyToAddresses < 0) {
                    throw new KettleException(BaseMessages.getString(PKG,
                            "Mail.Exception.CouldnotFindReplyToAddressesField", realReplyToAddresses));
                }
            }
        }

        // Contact Person
        if (!Const.isEmpty(meta.getContactPerson())) {
            // cache the position of the destination field
            if (data.indexOfContactPerson < 0) {
                String realContactPerson = meta.getContactPerson();
                data.indexOfContactPerson = data.previousRowMeta.indexOfValue(realContactPerson);
                if (data.indexOfContactPerson < 0) {
                    throw new KettleException(BaseMessages.getString(PKG,
                            "Mail.Exception.CouldnotFindContactPersonField", realContactPerson));
                }
            }
        }
        // Contact Phone
        if (!Const.isEmpty(meta.getContactPhone())) {
            // cache the position of the destination field
            if (data.indexOfContactPhone < 0) {
                String realContactPhone = meta.getContactPhone();
                data.indexOfContactPhone = data.previousRowMeta.indexOfValue(realContactPhone);
                if (data.indexOfContactPhone < 0) {
                    throw new KettleException(BaseMessages.getString(PKG,
                            "Mail.Exception.CouldnotFindContactPhoneField", realContactPhone));
                }
            }
        }
        // cache the position of the Server field
        if (data.indexOfServer < 0) {
            String realServer = meta.getServer();
            data.indexOfServer = data.previousRowMeta.indexOfValue(realServer);
            if (data.indexOfServer < 0) {
                throw new KettleException(
                        BaseMessages.getString(PKG, "Mail.Exception.CouldnotFindServerField", realServer));
            }
        }
        // Port
        if (!Const.isEmpty(meta.getPort())) {
            // cache the position of the port field
            if (data.indexOfPort < 0) {
                String realPort = meta.getPort();
                data.indexOfPort = data.previousRowMeta.indexOfValue(realPort);
                if (data.indexOfPort < 0) {
                    throw new KettleException(
                            BaseMessages.getString(PKG, "Mail.Exception.CouldnotFindPortField", realPort));
                }
            }
        }
        // Authentication
        if (meta.isUsingAuthentication()) {
            // cache the position of the Authentication user field
            if (data.indexOfAuthenticationUser < 0) {
                String realAuthenticationUser = meta.getAuthenticationUser();
                data.indexOfAuthenticationUser = data.previousRowMeta.indexOfValue(realAuthenticationUser);
                if (data.indexOfAuthenticationUser < 0) {
                    throw new KettleException(BaseMessages.getString(PKG,
                            "Mail.Exception.CouldnotFindAuthenticationUserField", realAuthenticationUser));
                }
            }

            // cache the position of the Authentication password field
            if (data.indexOfAuthenticationPass < 0) {
                String realAuthenticationPassword = meta.getAuthenticationPassword();
                data.indexOfAuthenticationPass = data.previousRowMeta.indexOfValue(realAuthenticationPassword);
                if (data.indexOfAuthenticationPass < 0) {
                    throw new KettleException(BaseMessages.getString(PKG,
                            "Mail.Exception.CouldnotFindAuthenticationPassField", realAuthenticationPassword));
                }
            }
        }
        // Mail Subject
        if (!Const.isEmpty(meta.getSubject())) {
            // cache the position of the subject field
            if (data.indexOfSubject < 0) {
                String realSubject = meta.getSubject();
                data.indexOfSubject = data.previousRowMeta.indexOfValue(realSubject);
                if (data.indexOfSubject < 0) {
                    throw new KettleException(BaseMessages.getString(PKG,
                            "Mail.Exception.CouldnotFindSubjectField", realSubject));
                }
            }
        }
        // Mail Comment
        if (!Const.isEmpty(meta.getComment())) {
            // cache the position of the comment field
            if (data.indexOfComment < 0) {
                String realComment = meta.getComment();
                data.indexOfComment = data.previousRowMeta.indexOfValue(realComment);
                if (data.indexOfComment < 0) {
                    throw new KettleException(BaseMessages.getString(PKG,
                            "Mail.Exception.CouldnotFindCommentField", realComment));
                }
            }
        }

        if (meta.isAttachContentFromField()) {
            // We are dealing with file content directly loaded from file
            // and not physical file
            String attachedContentField = meta.getAttachContentField();
            if (Const.isEmpty(attachedContentField)) {
                // Empty Field
                throw new KettleException(
                        BaseMessages.getString(PKG, "Mail.Exception.AttachedContentFieldEmpty"));
            }
            data.indexOfAttachedContent = data.previousRowMeta.indexOfValue(attachedContentField);
            if (data.indexOfComment < 0) {
                throw new KettleException(BaseMessages.getString(PKG,
                        "Mail.Exception.CouldnotFindAttachedContentField", attachedContentField));
            }
            // Attached content filename
            String attachedContentFileNameField = meta.getAttachContentFileNameField();
            if (Const.isEmpty(attachedContentFileNameField)) {
                // Empty Field
                throw new KettleException(
                        BaseMessages.getString(PKG, "Mail.Exception.AttachedContentFileNameFieldEmpty"));
            }
            data.IndexOfAttachedFilename = data.previousRowMeta.indexOfValue(attachedContentFileNameField);
            if (data.indexOfComment < 0) {
                throw new KettleException(
                        BaseMessages.getString(PKG, "Mail.Exception.CouldnotFindAttachedContentFileNameField",
                                attachedContentFileNameField));
            }

        } else {

            // Dynamic Zipfilename
            if (meta.isZipFilenameDynamic()) {
                // cache the position of the attached source filename field
                if (data.indexOfDynamicZipFilename < 0) {
                    String realZipFilename = meta.getDynamicZipFilenameField();
                    data.indexOfDynamicZipFilename = data.previousRowMeta.indexOfValue(realZipFilename);
                    if (data.indexOfDynamicZipFilename < 0) {
                        throw new KettleException(BaseMessages.getString(PKG,
                                "Mail.Exception.CouldnotSourceAttachedZipFilenameField", realZipFilename));
                    }
                }
            }
            data.zipFileLimit = Const.toLong(environmentSubstitute(meta.getZipLimitSize()), 0);
            if (data.zipFileLimit > 0) {
                data.zipFileLimit = data.zipFileLimit * 1048576; // Mo
            }

            if (!meta.isZipFilenameDynamic()) {
                data.ZipFilename = environmentSubstitute(meta.getZipFilename());
            }

            // Attached files
            if (meta.isDynamicFilename()) {
                // cache the position of the attached source filename field
                if (data.indexOfSourceFilename < 0) {
                    String realSourceattachedFilename = meta.getDynamicFieldname();
                    data.indexOfSourceFilename = data.previousRowMeta.indexOfValue(realSourceattachedFilename);
                    if (data.indexOfSourceFilename < 0) {
                        throw new KettleException(BaseMessages.getString(PKG,
                                "Mail.Exception.CouldnotSourceAttachedFilenameField",
                                realSourceattachedFilename));
                    }
                }

                // cache the position of the attached wildcard field
                if (!Const.isEmpty(meta.getSourceWildcard())) {
                    if (data.indexOfSourceWildcard < 0) {
                        String realSourceattachedWildcard = meta.getDynamicWildcard();
                        data.indexOfSourceWildcard = data.previousRowMeta
                                .indexOfValue(realSourceattachedWildcard);
                        if (data.indexOfSourceWildcard < 0) {
                            throw new KettleException(
                                    BaseMessages.getString(PKG, "Mail.Exception.CouldnotSourceAttachedWildcard",
                                            realSourceattachedWildcard));
                        }
                    }
                }
            } else {
                // static attached filenames
                data.realSourceFileFoldername = environmentSubstitute(meta.getSourceFileFoldername());
                data.realSourceWildcard = environmentSubstitute(meta.getSourceWildcard());
            }
        }

        // check embedded images
        if (meta.getEmbeddedImages() != null && meta.getEmbeddedImages().length > 0) {
            FileObject image = null;
            data.embeddedMimePart = new HashSet<MimeBodyPart>();
            try {
                for (int i = 0; i < meta.getEmbeddedImages().length; i++) {
                    String imageFile = environmentSubstitute(meta.getEmbeddedImages()[i]);
                    String contentID = environmentSubstitute(meta.getContentIds()[i]);
                    image = KettleVFS.getFileObject(imageFile);

                    if (image.exists() && image.getType() == FileType.FILE) {
                        // Create part for the image
                        MimeBodyPart imagePart = new MimeBodyPart();
                        // Load the image
                        URLDataSource fds = new URLDataSource(image.getURL());
                        imagePart.setDataHandler(new DataHandler(fds));
                        // Setting the header
                        imagePart.setHeader("Content-ID", "<" + contentID + ">");
                        // keep this part for further user
                        data.embeddedMimePart.add(imagePart);
                        logBasic(BaseMessages.getString(PKG, "Mail.Log.ImageAdded", imageFile));

                    } else {
                        logError(BaseMessages.getString(PKG, "Mail.Log.WrongImage", imageFile));
                    }
                }
            } catch (Exception e) {
                logError(BaseMessages.getString(PKG, "Mail.Error.AddingImage", e.getMessage()));
            } finally {
                if (image != null) {
                    try {
                        image.close();
                    } catch (Exception e) { /* Ignore */
                    }
                }
            }
        }

    } // end if first

    boolean sendToErrorRow = false;
    String errorMessage = null;

    try {
        // get values
        String maildestination = data.previousRowMeta.getString(r, data.indexOfDestination);
        if (Const.isEmpty(maildestination)) {
            throw new KettleException("Mail.Error.MailDestinationEmpty");
        }
        String maildestinationCc = null;
        if (data.indexOfDestinationCc > -1) {
            maildestinationCc = data.previousRowMeta.getString(r, data.indexOfDestinationCc);
        }
        String maildestinationBCc = null;
        if (data.indexOfDestinationBCc > -1) {
            maildestinationBCc = data.previousRowMeta.getString(r, data.indexOfDestinationBCc);
        }

        String mailsendername = null;
        if (data.indexOfSenderName > -1) {
            mailsendername = data.previousRowMeta.getString(r, data.indexOfSenderName);
        }
        String mailsenderaddress = data.previousRowMeta.getString(r, data.indexOfSenderAddress);

        // reply addresses
        String mailreplyToAddresses = null;
        if (data.indexOfReplyToAddresses > -1) {
            mailreplyToAddresses = data.previousRowMeta.getString(r, data.indexOfReplyToAddresses);
        }

        String contactperson = null;
        if (data.indexOfContactPerson > -1) {
            contactperson = data.previousRowMeta.getString(r, data.indexOfContactPerson);
        }
        String contactphone = null;
        if (data.indexOfContactPhone > -1) {
            contactphone = data.previousRowMeta.getString(r, data.indexOfContactPhone);
        }

        String servername = data.previousRowMeta.getString(r, data.indexOfServer);
        if (Const.isEmpty(servername)) {
            throw new KettleException("Mail.Error.MailServerEmpty");
        }
        int port = -1;
        if (data.indexOfPort > -1) {
            port = Const.toInt("" + data.previousRowMeta.getInteger(r, data.indexOfPort), -1);
        }

        String authuser = null;
        if (data.indexOfAuthenticationUser > -1) {
            authuser = data.previousRowMeta.getString(r, data.indexOfAuthenticationUser);
        }
        String authpass = null;
        if (data.indexOfAuthenticationPass > -1) {
            authpass = data.previousRowMeta.getString(r, data.indexOfAuthenticationPass);
        }

        String subject = null;
        if (data.indexOfSubject > -1) {
            subject = data.previousRowMeta.getString(r, data.indexOfSubject);
        }

        String comment = null;
        if (data.indexOfComment > -1) {
            comment = data.previousRowMeta.getString(r, data.indexOfComment);
        }

        // send email...
        sendMail(r, servername, port, mailsenderaddress, mailsendername, maildestination, maildestinationCc,
                maildestinationBCc, contactperson, contactphone, authuser, authpass, subject, comment,
                mailreplyToAddresses);

        putRow(getInputRowMeta(), r); // copy row to possible alternate rowset(s).); // copy row to output rowset(s);

        if (log.isRowLevel()) {
            logRowlevel(BaseMessages.getString(PKG, "Mail.Log.LineNumber",
                    getLinesRead() + " : " + getInputRowMeta().getString(r)));
        }

    } catch (Exception e) {
        if (getStepMeta().isDoingErrorHandling()) {
            sendToErrorRow = true;
            errorMessage = e.toString();
        } else {
            throw new KettleException(BaseMessages.getString(PKG, "Mail.Error.General"), e);
        }
        if (sendToErrorRow) {
            // Simply add this row to the error row
            putError(getInputRowMeta(), r, 1, errorMessage, null, "MAIL001");
        }
    }

    return true;
}

From source file:org.sakaiproject.email.impl.BasicEmailService.java

/**
 * Attaches a file as a body part to the multipart message
 *
 * @param attachment//from  w w w  . java 2  s  .c o  m
 * @throws MessagingException
 */
private MimeBodyPart createAttachmentPart(Attachment attachment) throws MessagingException {
    DataSource source = attachment.getDataSource();
    MimeBodyPart attachPart = new MimeBodyPart();

    attachPart.setDataHandler(new DataHandler(source));
    attachPart.setFileName(attachment.getFilename());

    if (attachment.getContentTypeHeader() != null) {
        attachPart.setHeader("Content-Type", attachment.getContentTypeHeader());
    }

    if (attachment.getContentDispositionHeader() != null) {
        attachPart.setHeader("Content-Disposition", attachment.getContentDispositionHeader());
    }

    return attachPart;
}

From source file:org.smartloli.kafka.eagle.api.email.MailServiceImpl.java

/** Send mail in HTML format */
private boolean sendHtmlMail(MailSenderInfo mailInfo) {
    boolean enableMailAlert = SystemConfigUtils.getBooleanProperty("kafka.eagle.mail.enable");
    if (enableMailAlert) {
        SaAuthenticatorInfo authenticator = null;
        Properties pro = mailInfo.getProperties();
        if (mailInfo.isValidate()) {
            authenticator = new SaAuthenticatorInfo(mailInfo.getUserName(), mailInfo.getPassword());
        }/*from w ww  . java2 s  .c  o  m*/
        Session sendMailSession = Session.getDefaultInstance(pro, authenticator);
        try {
            Message mailMessage = new MimeMessage(sendMailSession);
            Address from = new InternetAddress(mailInfo.getFromAddress());
            mailMessage.setFrom(from);
            Address[] to = new Address[mailInfo.getToAddress().split(",").length];
            int i = 0;
            for (String e : mailInfo.getToAddress().split(","))
                to[i++] = new InternetAddress(e);
            mailMessage.setRecipients(Message.RecipientType.TO, to);
            mailMessage.setSubject(mailInfo.getSubject());
            mailMessage.setSentDate(new Date());
            Multipart mainPart = new MimeMultipart();
            BodyPart html = new MimeBodyPart();
            html.setContent(mailInfo.getContent(), "text/html; charset=UTF-8");
            mainPart.addBodyPart(html);

            if (mailInfo.getImagesMap() != null && !mailInfo.getImagesMap().isEmpty()) {
                for (Entry<String, String> entry : mailInfo.getImagesMap().entrySet()) {
                    MimeBodyPart mbp = new MimeBodyPart();
                    File file = new File(entry.getValue());
                    FileDataSource fds = new FileDataSource(file);
                    mbp.setDataHandler(new DataHandler(fds));
                    try {
                        mbp.setFileName(MimeUtility.encodeWord(entry.getKey(), "UTF-8", null));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    mbp.setContentID(entry.getKey());
                    mbp.setHeader("Content-ID", "<image>");
                    mainPart.addBodyPart(mbp);
                }
            }

            List<File> list = mailInfo.getFileList();
            if (list != null && list.size() > 0) {
                for (File f : list) {
                    MimeBodyPart mbp = new MimeBodyPart();
                    FileDataSource fds = new FileDataSource(f.getAbsolutePath());
                    mbp.setDataHandler(new DataHandler(fds));
                    mbp.setFileName(f.getName());
                    mainPart.addBodyPart(mbp);
                }

                list.clear();
            }

            mailMessage.setContent(mainPart);
            // mailMessage.saveChanges();
            Transport.send(mailMessage);
            return true;
        } catch (MessagingException ex) {
            ex.printStackTrace();
        }
    }
    return false;
}