Example usage for javax.mail.internet MimeBodyPart MimeBodyPart

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

Introduction

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

Prototype

public MimeBodyPart() 

Source Link

Document

An empty MimeBodyPart object is created.

Usage

From source file:immf.MyHtmlEmail.java

public String embed(DataSource dataSource, String name, String nameCharset, String cid) throws EmailException {
    if (StringUtils.isEmpty(name)) {
        throw new EmailException("name cannot be null or empty");
    }//from   w w  w  .j a v  a 2s  . c  o m

    MimeBodyPart mbp = new MimeBodyPart();

    try {
        mbp.setDataHandler(new DataHandler(dataSource));
        Util.setFileName(mbp, name, nameCharset, null);
        //mbp.setFileName(name);
        mbp.setDisposition("inline");
        mbp.setContentID("<" + cid + ">");

        InlineImage ii = new InlineImage(cid, dataSource, mbp);
        this.inlineEmbeds.put(name, ii);

        return cid;
    } catch (MessagingException me) {
        throw new EmailException(me);
    }
}

From source file:fr.paris.lutece.portal.service.mail.MailUtil.java

/**
 * Send a calendar message.//  w  w  w  .  jav a  2s.c  om
 * @param strRecipientsTo The list of the main recipients email. Every
 *            recipient must be separated by the mail separator defined in
 *            config.properties
 * @param strRecipientsCc The recipients list of the carbon copies .
 * @param strRecipientsBcc The recipients list of the blind carbon copies .
 * @param strSenderName The sender name.
 * @param strSenderEmail The sender email address.
 * @param strSubject The message subject.
 * @param strMessage The HTML message.
 * @param strCalendarMessage The calendar message.
 * @param bCreateEvent True to create the event, false to remove it
 * @param transport the smtp transport object
 * @param session the smtp session object
 * @throws AddressException If invalid address
 * @throws SendFailedException If an error occurred during sending
 * @throws MessagingException If a messaging error occurred
 */
protected static void sendMessageCalendar(String strRecipientsTo, String strRecipientsCc,
        String strRecipientsBcc, String strSenderName, String strSenderEmail, String strSubject,
        String strMessage, String strCalendarMessage, boolean bCreateEvent, Transport transport,
        Session session) throws MessagingException, AddressException, SendFailedException {
    Message msg = prepareMessage(strRecipientsTo, strRecipientsCc, strRecipientsBcc, strSenderName,
            strSenderEmail, strSubject, session);
    msg.setHeader(HEADER_NAME, HEADER_VALUE);

    MimeMultipart multipart = new MimeMultipart();
    BodyPart msgBodyPart = new MimeBodyPart();
    msgBodyPart.setDataHandler(new DataHandler(
            new ByteArrayDataSource(strMessage, AppPropertiesService.getProperty(PROPERTY_MAIL_TYPE_HTML)
                    + AppPropertiesService.getProperty(PROPERTY_CHARSET))));

    multipart.addBodyPart(msgBodyPart);

    BodyPart calendarBodyPart = new MimeBodyPart();
    //        calendarBodyPart.addHeader( "Content-Class", "urn:content-classes:calendarmessage" );
    calendarBodyPart.setContent(strCalendarMessage,
            AppPropertiesService.getProperty(PROPERTY_MAIL_TYPE_CALENDAR)
                    + AppPropertiesService.getProperty(PROPERTY_CHARSET)
                    + AppPropertiesService.getProperty(PROPERTY_CALENDAR_SEPARATOR)
                    + AppPropertiesService.getProperty(
                            bCreateEvent ? PROPERTY_CALENDAR_METHOD_CREATE : PROPERTY_CALENDAR_METHOD_CANCEL));
    calendarBodyPart.addHeader(HEADER_NAME, CONSTANT_BASE64);
    multipart.addBodyPart(calendarBodyPart);

    msg.setContent(multipart);

    sendMessage(msg, transport);
}

From source file:it.eng.spagobi.tools.scheduler.dispatcher.UniqueMailDocumentDispatchChannel.java

public static MimeBodyPart zipAttachment(String zipFileName, Map mailOptions, File tempFolder) {
    logger.debug("IN");
    MimeBodyPart messageBodyPart = null;
    try {/* w w  w .j av  a  2s.c o m*/

        String nameSuffix = mailOptions.get(NAME_SUFFIX) != null ? (String) mailOptions.get(NAME_SUFFIX) : "";

        byte[] buffer = new byte[4096]; // Create a buffer for copying
        int bytesRead;

        // the zip
        String tempFolderPath = (String) mailOptions.get(TEMP_FOLDER_PATH);

        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        ZipOutputStream out = new ZipOutputStream(bout);

        logger.debug("File zip to write: " + tempFolderPath + File.separator + "zippedFile.zip");

        //files to zip
        String[] entries = tempFolder.list();

        for (int i = 0; i < entries.length; i++) {
            //File f = new File(tempFolder, entries[i]);
            File f = new File(tempFolder + File.separator + entries[i]);
            if (f.isDirectory())
                continue;//Ignore directory
            logger.debug("insert file: " + f.getName());
            FileInputStream in = new FileInputStream(f); // Stream to read file
            ZipEntry entry = new ZipEntry(f.getName()); // Make a ZipEntry
            out.putNextEntry(entry); // Store entry
            while ((bytesRead = in.read(buffer)) != -1)
                out.write(buffer, 0, bytesRead);
            in.close();
        }
        out.close();

        messageBodyPart = new MimeBodyPart();
        DataSource source = new ByteArrayDataSource(bout.toByteArray(), "application/zip");
        messageBodyPart.setDataHandler(new DataHandler(source));

        messageBodyPart.setFileName(zipFileName + nameSuffix + ".zip");

    } catch (Exception e) {
        logger.error("Error while creating the zip", e);
        return null;
    }

    logger.debug("OUT");

    return messageBodyPart;
}

From source file:nl.nn.adapterframework.senders.MailSender.java

protected String sendEmail(String from, String subject, String threadTopic, String message, String messageType,
        String messageBase64, String charset, Collection recipients, Collection attachments)
        throws SenderException {

    StringBuffer sb = new StringBuffer();

    if (recipients == null || recipients.size() == 0) {
        throw new SenderException("MailSender [" + getName() + "] has no recipients for message");
    }//from  w  w w  .  j a  v a 2  s .  c o  m
    if (StringUtils.isEmpty(from)) {
        from = defaultFrom;
    }
    if (StringUtils.isEmpty(subject)) {
        subject = defaultSubject;
    }
    log.debug("MailSender [" + getName() + "] requested to send message from [" + from + "] subject [" + subject
            + "] to #recipients [" + recipients.size() + "]");

    if (StringUtils.isEmpty(messageType)) {
        messageType = defaultMessageType;
    }

    if (StringUtils.isEmpty(messageBase64)) {
        messageBase64 = defaultMessageBase64;
    }

    try {
        if (log.isDebugEnabled()) {
            sb.append("MailSender [" + getName() + "] sending message ");
            sb.append("[smtpHost=" + smtpHost);
            sb.append("[from=" + from + "]");
            sb.append("[subject=" + subject + "]");
            sb.append("[threadTopic=" + threadTopic + "]");
            sb.append("[text=" + message + "]");
            sb.append("[type=" + messageType + "]");
            sb.append("[base64=" + messageBase64 + "]");
        }

        if ("true".equalsIgnoreCase(messageBase64) && StringUtils.isNotEmpty(message)) {
            message = decodeBase64ToString(message);
        }

        // construct a message  
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(from));
        msg.setSubject(subject, charset);
        if (StringUtils.isNotEmpty(threadTopic)) {
            msg.setHeader("Thread-Topic", threadTopic);
        }
        Iterator iter = recipients.iterator();
        boolean recipientsFound = false;
        while (iter.hasNext()) {
            Element recipientElement = (Element) iter.next();
            String recipient = XmlUtils.getStringValue(recipientElement);
            if (StringUtils.isNotEmpty(recipient)) {
                String typeAttr = recipientElement.getAttribute("type");
                Message.RecipientType recipientType = Message.RecipientType.TO;
                if ("cc".equalsIgnoreCase(typeAttr)) {
                    recipientType = Message.RecipientType.CC;
                }
                if ("bcc".equalsIgnoreCase(typeAttr)) {
                    recipientType = Message.RecipientType.BCC;
                }
                msg.addRecipient(recipientType, new InternetAddress(recipient));
                recipientsFound = true;
                if (log.isDebugEnabled()) {
                    sb.append("[recipient(" + typeAttr + ")=" + recipient + "]");
                }
            } else {
                log.debug("empty recipient found, ignoring");
            }
        }
        if (!recipientsFound) {
            throw new SenderException("MailSender [" + getName() + "] did not find any valid recipients");
        }

        String messageTypeWithCharset;
        if (charset == null) {
            charset = System.getProperty("mail.mime.charset");
            if (charset == null) {
                charset = System.getProperty("file.encoding");
            }
        }
        if (charset != null) {
            messageTypeWithCharset = messageType + ";charset=" + charset;
        } else {
            messageTypeWithCharset = messageType;
        }
        log.debug("MailSender [" + getName() + "] uses encoding [" + messageTypeWithCharset + "]");

        if (attachments == null || attachments.size() == 0) {
            //msg.setContent(message, messageType);
            msg.setContent(message, messageTypeWithCharset);
        } else {
            Multipart multipart = new MimeMultipart();
            BodyPart messageBodyPart = new MimeBodyPart();
            //messageBodyPart.setContent(message, messageType);
            messageBodyPart.setContent(message, messageTypeWithCharset);
            multipart.addBodyPart(messageBodyPart);

            iter = attachments.iterator();
            while (iter.hasNext()) {
                Element attachmentElement = (Element) iter.next();
                String attachmentText = XmlUtils.getStringValue(attachmentElement);
                String attachmentName = attachmentElement.getAttribute("name");
                String attachmentUrl = attachmentElement.getAttribute("url");
                String attachmentType = attachmentElement.getAttribute("type");
                String attachmentBase64 = attachmentElement.getAttribute("base64");
                if (StringUtils.isEmpty(attachmentType)) {
                    attachmentType = getDefaultAttachmentType();
                }
                if (StringUtils.isEmpty(attachmentName)) {
                    attachmentName = getDefaultAttachmentName();
                }
                log.debug("found attachment [" + attachmentName + "] type [" + attachmentType + "] url ["
                        + attachmentUrl + "]contents [" + attachmentText + "]");

                messageBodyPart = new MimeBodyPart();

                DataSource attachmentDataSource;
                if (!StringUtils.isEmpty(attachmentUrl)) {
                    attachmentDataSource = new URLDataSource(new URL(attachmentUrl));
                    messageBodyPart.setDataHandler(new DataHandler(attachmentDataSource));
                }

                messageBodyPart.setFileName(attachmentName);

                if ("true".equalsIgnoreCase(attachmentBase64)) {
                    messageBodyPart.setDataHandler(decodeBase64(attachmentText));
                } else {
                    messageBodyPart.setText(attachmentText);
                }

                multipart.addBodyPart(messageBodyPart);
            }
            msg.setContent(multipart);
        }

        log.debug(sb.toString());
        msg.setSentDate(new Date());
        msg.saveChanges();
        // send the message
        putOnTransport(msg);
        // return the mail in mail-safe from
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        msg.writeTo(out);
        byte[] byteArray = out.toByteArray();
        return Misc.byteArrayToString(byteArray, "\n", false);
    } catch (Exception e) {
        throw new SenderException("MailSender got error", e);
    }
}

From source file:org.apache.camel.component.mail.MailBinding.java

protected void addAttachmentsToMultipart(MimeMultipart multipart, String partDisposition, Exchange exchange)
        throws MessagingException {
    LOG.trace("Adding attachments +++ start +++");
    int i = 0;//from w  w w  . j a va 2  s.  c  o m
    for (Map.Entry<String, DataHandler> entry : exchange.getIn().getAttachments().entrySet()) {
        String attachmentFilename = entry.getKey();
        DataHandler handler = entry.getValue();

        if (LOG.isTraceEnabled()) {
            LOG.trace("Attachment #" + i + ": Disposition: " + partDisposition);
            LOG.trace("Attachment #" + i + ": DataHandler: " + handler);
            LOG.trace("Attachment #" + i + ": FileName: " + attachmentFilename);
        }
        if (handler != null) {
            if (shouldAddAttachment(exchange, attachmentFilename, handler)) {
                // Create another body part
                BodyPart messageBodyPart = new MimeBodyPart();
                // Set the data handler to the attachment
                messageBodyPart.setDataHandler(handler);

                if (attachmentFilename.toLowerCase().startsWith("cid:")) {
                    // add a Content-ID header to the attachment
                    // must use angle brackets according to RFC: http://www.ietf.org/rfc/rfc2392.txt
                    messageBodyPart.addHeader("Content-ID", "<" + attachmentFilename.substring(4) + ">");
                    // Set the filename without the cid
                    messageBodyPart.setFileName(attachmentFilename.substring(4));
                } else {
                    // Set the filename
                    messageBodyPart.setFileName(attachmentFilename);
                }

                LOG.trace("Attachment #" + i + ": ContentType: " + messageBodyPart.getContentType());

                if (contentTypeResolver != null) {
                    String contentType = contentTypeResolver.resolveContentType(attachmentFilename);
                    LOG.trace("Attachment #" + i + ": Using content type resolver: " + contentTypeResolver
                            + " resolved content type as: " + contentType);
                    if (contentType != null) {
                        String value = contentType + "; name=" + attachmentFilename;
                        messageBodyPart.setHeader("Content-Type", value);
                        LOG.trace("Attachment #" + i + ": ContentType: " + messageBodyPart.getContentType());
                    }
                }

                // Set Disposition
                messageBodyPart.setDisposition(partDisposition);
                // Add part to multipart
                multipart.addBodyPart(messageBodyPart);
            } else {
                LOG.trace("shouldAddAttachment: false");
            }
        } else {
            LOG.warn("Cannot add attachment: " + attachmentFilename + " as DataHandler is null");
        }
        i++;
    }
    LOG.trace("Adding attachments +++ done +++");
}

From source file:org.pentaho.di.trans.steps.mail.Mail.java

public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException {
    meta = (MailMeta) smi;/*  w  w  w.ja v  a2  s.com*/
    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.xwiki.commons.internal.DefaultMailSender.java

private MimeBodyPart createAttachmentPart(Attachment attachment) {
    try {//from   w w  w .ja  v a 2 s.  com
        String name = attachment.getFilename();
        byte[] stream = attachment.getContent();
        File temp = File.createTempFile("tmpfile", ".tmp");
        FileOutputStream fos = new FileOutputStream(temp);
        fos.write(stream);
        fos.close();
        DataSource source = new FileDataSource(temp);
        MimeBodyPart part = new MimeBodyPart();
        String mimeType = MimeTypesUtil.getMimeTypeFromFilename(name);

        part.setDataHandler(new DataHandler(source));
        part.setHeader("Content-Type", mimeType);
        part.setFileName(name);
        part.setContentID("<" + name + ">");
        part.setDisposition("inline");

        temp.deleteOnExit();
        return part;
    } catch (Exception e) {
        return new MimeBodyPart();
    }
}

From source file:org.georchestra.ldapadmin.ws.emails.EmailController.java

/**
 * Send EmailEntry to smtp server/*from w w  w .j  av a2  s  .c om*/
 *
 * @param email email to send
 * @throws NameNotFoundException if recipient cannot be found in LDAP server
 * @throws DataServiceException if LDAP server is not available
 * @throws MessagingException if some field of email cannot be encoded (malformed email address)
 */
private void send(EmailEntry email) throws NameNotFoundException, DataServiceException, MessagingException {

    final Properties props = System.getProperties();
    props.put("mail.smtp.host", this.emailFactory.getSmtpHost());
    props.put("mail.protocol.port", this.emailFactory.getSmtpPort());

    final Session session = Session.getInstance(props, null);
    final MimeMessage message = new MimeMessage(session);

    Account recipient = this.accountDao.findByUID(email.getRecipient());
    InternetAddress[] senders = {
            new InternetAddress(this.accountDao.findByUID(email.getSender()).getEmail()) };

    message.addFrom(senders);
    message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient.getEmail()));
    message.setSubject(email.getSubject());
    message.setHeader("Date", (new MailDateFormat()).format(email.getDate()));

    // Mail content
    Multipart multiPart = new MimeMultipart("alternative");

    // attachments
    for (Attachment att : email.getAttachments()) {
        MimeBodyPart mbp = new MimeBodyPart();
        mbp.setDataHandler(new DataHandler(new ByteArrayDataSource(att.getContent(), att.getMimeType())));
        mbp.setFileName(att.getName());
        multiPart.addBodyPart(mbp);
    }

    // html part
    MimeBodyPart htmlPart = new MimeBodyPart();
    htmlPart.setContent(email.getBody(), "text/html; charset=utf-8");
    multiPart.addBodyPart(htmlPart);

    message.setContent(multiPart);

    // Send message
    Transport.send(message);
}

From source file:org.georchestra.console.ws.emails.EmailController.java

/**
 * Send EmailEntry to smtp server//from   w  ww.  j  a va  2  s.  c  o m
 *
 * @param email email to send
 * @throws NameNotFoundException if recipient cannot be found in LDAP server
 * @throws DataServiceException if LDAP server is not available
 * @throws MessagingException if some field of email cannot be encoded (malformed email address)
 */
private void send(EmailEntry email) throws NameNotFoundException, DataServiceException, MessagingException {

    final Session session = Session.getInstance(System.getProperties(), null);
    session.getProperties().setProperty("mail.smtp.host", this.emailFactory.getSmtpHost());
    session.getProperties().setProperty("mail.smtp.port",
            (new Integer(this.emailFactory.getSmtpPort())).toString());
    final MimeMessage message = new MimeMessage(session);

    Account recipient = this.accountDao.findByUID(email.getRecipient());
    InternetAddress[] senders = {
            new InternetAddress(this.accountDao.findByUID(email.getSender()).getEmail()) };

    message.addFrom(senders);
    message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient.getEmail()));
    message.setSubject(email.getSubject());
    message.setHeader("Date", (new MailDateFormat()).format(email.getDate()));

    // Mail content
    Multipart multiPart = new MimeMultipart("alternative");

    // attachments
    for (Attachment att : email.getAttachments()) {
        MimeBodyPart mbp = new MimeBodyPart();
        mbp.setDataHandler(new DataHandler(new ByteArrayDataSource(att.getContent(), att.getMimeType())));
        mbp.setFileName(att.getName());
        multiPart.addBodyPart(mbp);
    }

    // html part
    MimeBodyPart htmlPart = new MimeBodyPart();
    htmlPart.setContent(email.getBody(), "text/html; charset=utf-8");
    multiPart.addBodyPart(htmlPart);

    message.setContent(multiPart);

    // Send message
    Transport.send(message);
}

From source file:com.emc.kibana.emailer.KibanaEmailer.java

private static void sendFileEmail(String security) {

    final String username = smtpUsername;
    final String password = smtpPassword;

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

    // Setup mail server
    properties.setProperty("mail.smtp.host", smtpHost);

    if (security.equals(SMTP_SECURITY_TLS)) {
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.starttls.enable", "true");
        properties.put("mail.smtp.host", smtpHost);
        properties.put("mail.smtp.port", smtpPort);
    } else if (security.equals(SMTP_SECURITY_SSL)) {
        properties.put("mail.smtp.socketFactory.port", smtpPort);
        properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.port", smtpPort);
    }/*from w  w  w  .  j  a v  a  2  s .  c om*/

    Session session = Session.getInstance(properties, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }
    });

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

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

        // Set To: header field of the header.
        for (String destinationAddress : destinationAddressList) {
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(destinationAddress));
        }

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

        // Create the message part 
        BodyPart messageBodyPart = new MimeBodyPart();

        StringBuffer bodyBuffer = new StringBuffer(mailBody);
        if (!kibanaUrls.isEmpty()) {
            bodyBuffer.append("\n\n");
        }

        // Add urls info to e-mail
        for (Map<String, String> kibanaUrl : kibanaUrls) {
            // Add urls to e-mail
            String urlName = kibanaUrl.get(NAME_KEY);
            String reportUrl = kibanaUrl.get(URL_KEY);
            if (urlName != null && reportUrl != null) {
                bodyBuffer.append("- ").append(urlName).append(": ").append(reportUrl).append("\n\n\n");
            }
        }

        // Fill the message
        messageBodyPart.setText(bodyBuffer.toString());

        // Create a multipart message
        Multipart multipart = new MimeMultipart();

        // Set text message part
        multipart.addBodyPart(messageBodyPart);

        // Part two is attachments
        for (Map<String, String> kibanaScreenCapture : kibanaScreenCaptures) {
            messageBodyPart = new MimeBodyPart();
            String absoluteFilename = kibanaScreenCapture.get(ABSOLUE_FILE_NAME_KEY);
            String filename = kibanaScreenCapture.get(FILE_NAME_KEY);
            DataSource source = new FileDataSource(absoluteFilename);
            messageBodyPart.setDataHandler(new DataHandler(source));
            messageBodyPart.setFileName(filename);

            multipart.addBodyPart(messageBodyPart);
        }

        // Send the complete message parts
        message.setContent(multipart);

        // Send message
        Transport.send(message);
        logger.info("Sent mail message successfully");
    } catch (MessagingException mex) {
        throw new RuntimeException(mex);
    }
}