Example usage for javax.mail.internet MimeBodyPart setFileName

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

Introduction

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

Prototype

@Override
public void setFileName(String filename) throws MessagingException 

Source Link

Document

Set the filename associated with this body part, if possible.

Usage

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

private MimeBodyPart zipAttachment(byte[] attach, String containedFileName, String zipFileName,
        String nameSuffix, String fileExtension) {
    MimeBodyPart messageBodyPart = null;
    try {// ww  w. j  a  v  a 2s.  co  m

        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        ZipOutputStream zipOut = new ZipOutputStream(bout);
        String entryName = containedFileName + nameSuffix + fileExtension;
        zipOut.putNextEntry(new ZipEntry(entryName));
        zipOut.write(attach);
        zipOut.closeEntry();

        zipOut.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) {
        // TODO: handle exception            
    }
    return messageBodyPart;
}

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

private void addAttachedContent(String filename, String fileContent) throws Exception {
    // create a data source

    MimeBodyPart mbp = new MimeBodyPart();
    // get a data Handler to manipulate this file type;
    mbp.setDataHandler(new DataHandler(new ByteArrayDataSource(fileContent.getBytes(), "application/x-any")));
    // include the file in the data source
    mbp.setFileName(filename);
    // add the part with the file in the BodyPart();
    data.parts.addBodyPart(mbp);/*from  w  w w  .  j  ava2s.  c o m*/

}

From source file:com.stratelia.silverpeas.infoLetter.control.InfoLetterSessionController.java

public String[] notifyExternals(InfoLetterPublicationPdC ilp, String server, List<String> emails) {
    // Retrieve SMTP server information
    String host = getSmtpHost();//from   w ww .j  a v  a2  s  .c o m
    boolean isSmtpAuthentication = isSmtpAuthentication();
    int smtpPort = getSmtpPort();
    String smtpUser = getSmtpUser();
    String smtpPwd = getSmtpPwd();
    boolean isSmtpDebug = isSmtpDebug();

    List<String> emailErrors = new ArrayList<String>();

    if (emails.size() > 0) {

        // Corps et sujet du message
        String subject = getString("infoLetter.emailSubject") + ilp.getName();
        // Email du publieur
        String from = getUserDetail().geteMail();
        // create some properties and get the default Session
        Properties props = System.getProperties();
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.auth", String.valueOf(isSmtpAuthentication));

        Session session = Session.getInstance(props, null);
        session.setDebug(isSmtpDebug); // print on the console all SMTP messages.

        SilverTrace.info("infoLetter", "InfoLetterSessionController.notifyExternals()",
                "root.MSG_GEN_PARAM_VALUE", "subject = " + subject);
        SilverTrace.info("infoLetter", "InfoLetterSessionController.notifyExternals()",
                "root.MSG_GEN_PARAM_VALUE", "from = " + from);
        SilverTrace.info("infoLetter", "InfoLetterSessionController.notifyExternals()",
                "root.MSG_GEN_PARAM_VALUE", "host= " + host);

        try {
            // create a message
            MimeMessage msg = new MimeMessage(session);
            msg.setFrom(new InternetAddress(from));
            msg.setSubject(subject, CharEncoding.UTF_8);
            ForeignPK foreignKey = new ForeignPK(ilp.getPK().getId(), getComponentId());
            // create and fill the first message part
            MimeBodyPart mbp1 = new MimeBodyPart();
            List<SimpleDocument> contents = AttachmentServiceFactory.getAttachmentService()
                    .listDocumentsByForeignKeyAndType(foreignKey, DocumentType.wysiwyg,
                            I18NHelper.defaultLanguage);
            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
            for (SimpleDocument content : contents) {
                AttachmentServiceFactory.getAttachmentService().getBinaryContent(buffer, content.getPk(),
                        content.getLanguage());
            }
            mbp1.setDataHandler(
                    new DataHandler(new ByteArrayDataSource(
                            replaceFileServerWithLocal(
                                    IOUtils.toString(buffer.toByteArray(), CharEncoding.UTF_8), server),
                            MimeTypes.HTML_MIME_TYPE)));
            IOUtils.closeQuietly(buffer);
            // Fichiers joints
            WAPrimaryKey publiPK = ilp.getPK();
            publiPK.setComponentName(getComponentId());
            publiPK.setSpace(getSpaceId());

            // create the Multipart and its parts to it
            String mimeMultipart = getSettings().getString("SMTPMimeMultipart", "related");
            Multipart mp = new MimeMultipart(mimeMultipart);
            mp.addBodyPart(mbp1);

            // Images jointes
            List<SimpleDocument> fichiers = AttachmentServiceFactory.getAttachmentService()
                    .listDocumentsByForeignKeyAndType(foreignKey, DocumentType.image, null);
            for (SimpleDocument attachment : fichiers) {
                // create the second message part
                MimeBodyPart mbp2 = new MimeBodyPart();

                // attach the file to the message
                FileDataSource fds = new FileDataSource(attachment.getAttachmentPath());
                mbp2.setDataHandler(new DataHandler(fds));
                // For Displaying images in the mail
                mbp2.setFileName(attachment.getFilename());
                mbp2.setHeader("Content-ID", attachment.getFilename());
                SilverTrace.info("infoLetter", "InfoLetterSessionController.notifyExternals()",
                        "root.MSG_GEN_PARAM_VALUE", "content-ID= " + mbp2.getContentID());

                // create the Multipart and its parts to it
                mp.addBodyPart(mbp2);
            }

            // Fichiers joints
            fichiers = AttachmentServiceFactory.getAttachmentService()
                    .listDocumentsByForeignKeyAndType(foreignKey, DocumentType.attachment, null);

            if (!fichiers.isEmpty()) {
                for (SimpleDocument attachment : fichiers) {
                    // create the second message part
                    MimeBodyPart mbp2 = new MimeBodyPart();

                    // attach the file to the message
                    FileDataSource fds = new FileDataSource(attachment.getAttachmentPath());
                    mbp2.setDataHandler(new DataHandler(fds));
                    mbp2.setFileName(attachment.getFilename());
                    // For Displaying images in the mail
                    mbp2.setHeader("Content-ID", attachment.getFilename());
                    SilverTrace.info("infoLetter", "InfoLetterSessionController.notifyExternals()",
                            "root.MSG_GEN_PARAM_VALUE", "content-ID= " + mbp2.getContentID());

                    // create the Multipart and its parts to it
                    mp.addBodyPart(mbp2);
                }
            }

            // add the Multipart to the message
            msg.setContent(mp);
            // set the Date: header
            msg.setSentDate(new Date());
            // create a Transport connection (TCP)
            Transport transport = session.getTransport("smtp");

            InternetAddress[] address = new InternetAddress[1];
            for (String email : emails) {
                try {
                    address[0] = new InternetAddress(email);
                    msg.setRecipients(Message.RecipientType.TO, address);
                    // add Transport Listener to the transport connection.
                    if (isSmtpAuthentication) {
                        SilverTrace.info("infoLetter", "InfoLetterSessionController.notifyExternals()",
                                "root.MSG_GEN_PARAM_VALUE",
                                "host = " + host + " m_Port=" + smtpPort + " m_User=" + smtpUser);
                        transport.connect(host, smtpPort, smtpUser, smtpPwd);
                        msg.saveChanges();
                    } else {
                        transport.connect();
                    }
                    transport.sendMessage(msg, address);
                } catch (Exception ex) {
                    SilverTrace.error("infoLetter", "InfoLetterSessionController.notifyExternals()",
                            "root.MSG_GEN_PARAM_VALUE", "Email = " + email,
                            new InfoLetterException(
                                    "com.stratelia.silverpeas.infoLetter.control.InfoLetterSessionController",
                                    SilverpeasRuntimeException.ERROR, ex.getMessage(), ex));
                    emailErrors.add(email);
                } finally {
                    if (transport != null) {
                        try {
                            transport.close();
                        } catch (Exception e) {
                            SilverTrace.error("infoLetter", "InfoLetterSessionController.notifyExternals()",
                                    "root.EX_IGNORED", "ClosingTransport", e);
                        }
                    }
                }
            }
        } catch (Exception e) {
            throw new InfoLetterException(
                    "com.stratelia.silverpeas.infoLetter.control.InfoLetterSessionController",
                    SilverpeasRuntimeException.ERROR, e.getMessage(), e);
        }
    }
    return emailErrors.toArray(new String[emailErrors.size()]);
}

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

private void addAttachedFilePart(FileObject file) throws Exception {
    // create a data source

    MimeBodyPart files = new MimeBodyPart();
    // create a data source
    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();
    data.parts.addBodyPart(files);//www . ja v a 2  s  . com
    if (isDetailed()) {
        logDetailed(BaseMessages.getString(PKG, "Mail.Log.AttachedFile", fds.getName()));
    }

}

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

public boolean dispatch(BIObject document, byte[] executionOutput) {
    Map parametersMap;//w  w w.  java2 s .  c o  m
    String contentType;
    String fileExtension;
    IDataStore emailDispatchDataStore;
    String nameSuffix;
    String descriptionSuffix;
    String containedFileName;
    String zipFileName;
    boolean reportNameInSubject;

    logger.debug("IN");
    try {
        parametersMap = dispatchContext.getParametersMap();
        contentType = dispatchContext.getContentType();
        fileExtension = dispatchContext.getFileExtension();
        emailDispatchDataStore = dispatchContext.getEmailDispatchDataStore();
        nameSuffix = dispatchContext.getNameSuffix();
        descriptionSuffix = dispatchContext.getDescriptionSuffix();
        containedFileName = dispatchContext.getContainedFileName() != null
                && !dispatchContext.getContainedFileName().equals("") ? dispatchContext.getContainedFileName()
                        : document.getName();
        zipFileName = dispatchContext.getZipMailName() != null && !dispatchContext.getZipMailName().equals("")
                ? dispatchContext.getZipMailName()
                : document.getName();
        reportNameInSubject = dispatchContext.isReportNameInSubject();

        String smtphost = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.smtphost");
        String smtpport = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.smtpport");
        String smtpssl = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.useSSL");
        logger.debug(smtphost + " " + smtpport + " use SSL: " + smtpssl);

        //Custom Trusted Store Certificate Options
        String trustedStorePath = SingletonConfig.getInstance()
                .getConfigValue("MAIL.PROFILES.trustedStore.file");
        String trustedStorePassword = SingletonConfig.getInstance()
                .getConfigValue("MAIL.PROFILES.trustedStore.password");

        int smptPort = 25;

        if ((smtphost == null) || smtphost.trim().equals(""))
            throw new Exception("Smtp host not configured");
        if ((smtpport == null) || smtpport.trim().equals("")) {
            throw new Exception("Smtp host not configured");
        } else {
            smptPort = Integer.parseInt(smtpport);
        }

        String from = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.from");
        if ((from == null) || from.trim().equals(""))
            from = "spagobi.scheduler@eng.it";
        String user = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.user");
        if ((user == null) || user.trim().equals("")) {
            logger.debug("Smtp user not configured");
            user = null;
        }
        //   throw new Exception("Smtp user not configured");
        String pass = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.password");
        if ((pass == null) || pass.trim().equals("")) {
            logger.debug("Smtp password not configured");
        }
        //   throw new Exception("Smtp password not configured");

        String mailSubj = dispatchContext.getMailSubj();
        mailSubj = StringUtilities.substituteParametersInString(mailSubj, parametersMap, null, false);

        String mailTxt = dispatchContext.getMailTxt();

        String[] recipients = findRecipients(dispatchContext, document, emailDispatchDataStore);
        if (recipients == null || recipients.length == 0) {
            logger.error("No recipients found for email sending!!!");
            return false;
        }

        //Set the host smtp address
        Properties props = new Properties();
        props.put("mail.smtp.host", smtphost);
        props.put("mail.smtp.port", Integer.toString(smptPort));

        // open session
        Session session = null;

        // create autheticator object
        Authenticator auth = null;
        if (user != null) {
            auth = new SMTPAuthenticator(user, pass);
            props.put("mail.smtp.auth", "true");
            //SSL Connection
            if (smtpssl.equals("true")) {
                Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
                //props.put("mail.smtp.debug", "true");          
                props.put("mail.smtps.auth", "true");
                props.put("mail.smtps.socketFactory.port", Integer.toString(smptPort));
                if ((!StringUtilities.isEmpty(trustedStorePath))) {
                    /* Dynamic configuration of trustedstore for CA
                     * Using Custom SSLSocketFactory to inject certificates directly from specified files
                     */
                    //System.setProperty("java.security.debug","certpath");
                    //System.setProperty("javax.net.debug","ssl ");
                    props.put("mail.smtps.socketFactory.class", CUSTOM_SSL_FACTORY);

                } else {
                    //System.setProperty("java.security.debug","certpath");
                    //System.setProperty("javax.net.debug","ssl ");
                    props.put("mail.smtps.socketFactory.class", DEFAULT_SSL_FACTORY);
                }
                props.put("mail.smtp.socketFactory.fallback", "false");
            }

            //session = Session.getDefaultInstance(props, auth);
            session = Session.getInstance(props, auth);
            //session.setDebug(true);
            //session.setDebugOut(null);
            logger.info("Session.getInstance(props, auth)");

        } else {
            //session = Session.getDefaultInstance(props);
            session = Session.getInstance(props);
            logger.info("Session.getInstance(props)");
        }

        // create a message
        Message msg = new MimeMessage(session);
        // set the from and to address
        InternetAddress addressFrom = new InternetAddress(from);
        msg.setFrom(addressFrom);
        InternetAddress[] addressTo = new InternetAddress[recipients.length];
        for (int i = 0; i < recipients.length; i++) {
            addressTo[i] = new InternetAddress(recipients[i]);
        }
        msg.setRecipients(Message.RecipientType.TO, addressTo);
        // Setting the Subject and Content Type

        String subject = mailSubj;

        if (reportNameInSubject) {
            subject += " " + document.getName() + nameSuffix;
        }

        msg.setSubject(subject);
        // create and fill the first message part
        MimeBodyPart mbp1 = new MimeBodyPart();
        mbp1.setText(mailTxt + "\n" + descriptionSuffix);
        // create the second message part
        MimeBodyPart mbp2 = new MimeBodyPart();
        // attach the file to the message

        SchedulerDataSource sds = null;
        //if zip requested
        if (dispatchContext.isZipMailDocument()) {
            mbp2 = zipAttachment(executionOutput, containedFileName, zipFileName, nameSuffix, fileExtension);
        }
        //else 
        else {
            sds = new SchedulerDataSource(executionOutput, contentType,
                    containedFileName + nameSuffix + fileExtension);
            mbp2.setDataHandler(new DataHandler(sds));
            mbp2.setFileName(sds.getName());
        }

        // create the Multipart and add its parts to it
        Multipart mp = new MimeMultipart();
        mp.addBodyPart(mbp1);
        mp.addBodyPart(mbp2);
        // add the Multipart to the message
        msg.setContent(mp);
        // send message
        if ((smtpssl.equals("true")) && (!StringUtilities.isEmpty(user)) && (!StringUtilities.isEmpty(pass))) {
            //USE SSL Transport comunication with SMTPS
            Transport transport = session.getTransport("smtps");
            transport.connect(smtphost, smptPort, user, pass);
            transport.sendMessage(msg, msg.getAllRecipients());
            transport.close();
        } else {
            //Use normal SMTP
            Transport.send(msg);
        }
    } catch (Exception e) {
        logger.error("Error while sending schedule result mail", e);
        return false;
    } finally {
        logger.debug("OUT");
    }
    return true;
}

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

public MimeBodyPart toMimeBodyPart(Multipart mp, lucee.runtime.config.Config config, Attachment att)
        throws MessagingException {

    MimeBodyPart mbp = new MimeBodyPart();

    // set Data Source
    String strRes = att.getAbsolutePath();
    if (!StringUtil.isEmpty(strRes)) {

        mbp.setDataHandler(new DataHandler(new ResourceDataSource(config.getResource(strRes))));
    } else/*from  ww  w  .ja v  a 2 s  .  com*/
        mbp.setDataHandler(new DataHandler(new URLDataSource2(att.getURL())));

    mbp.setFileName(att.getFileName());
    if (!StringUtil.isEmpty(att.getType()))
        mbp.setHeader("Content-Type", att.getType());
    if (!StringUtil.isEmpty(att.getDisposition())) {
        mbp.setDisposition(att.getDisposition());
        /*if(mp instanceof MimeMultipart) {
           ((MimeMultipart)mp).setSubType("related");
        }*/

    }
    if (!StringUtil.isEmpty(att.getContentID()))
        mbp.setContentID(att.getContentID());

    return mbp;
}

From source file:com.alvexcore.repo.emails.impl.ExtendedEmailMessage.java

@Override
public void send(List<String> to, List<String> cc, List<String> bcc, String subject, String body,
        List<NodeRef> attachments, boolean html) throws Exception {
    EmailConfig config = getConfig();//from   w ww . ja  va  2 s  .c o m
    EmailProvider provider = getEmailProvider(config.getProviderId());
    Properties props = System.getProperties();
    String prefix = "mail." + provider.getOutgoingProto() + ".";
    props.put(prefix + "host", provider.getOutgoingServer());
    props.put(prefix + "port", provider.getOutgoingPort());
    props.put(prefix + "auth", "true");
    Session session = Session.getInstance(props, null);
    Message msg = new MimeMessage(session);
    msg.setFrom(new InternetAddress(config.getAddress(), config.getRealName()));
    if (to != null) {
        InternetAddress[] recipients = new InternetAddress[to.size()];
        for (int i = 0; i < to.size(); i++)
            recipients[i] = new InternetAddress(to.get(i));
        msg.setRecipients(Message.RecipientType.TO, recipients);
    }

    if (cc != null) {
        InternetAddress[] recipients = new InternetAddress[cc.size()];
        for (int i = 0; i < cc.size(); i++)
            recipients[i] = new InternetAddress(cc.get(i));
        msg.setRecipients(Message.RecipientType.CC, recipients);
    }

    if (bcc != null) {
        InternetAddress[] recipients = new InternetAddress[bcc.size()];
        for (int i = 0; i < bcc.size(); i++)
            recipients[i] = new InternetAddress(bcc.get(i));
        msg.setRecipients(Message.RecipientType.BCC, recipients);
    }

    msg.setSubject(subject);
    msg.setHeader("X-Mailer", "Alvex Emailer");
    msg.setSentDate(new Date());

    MimeBodyPart messageBodyPart = new MimeBodyPart();
    Multipart multipart = new MimeMultipart();

    if (body != null) {
        messageBodyPart = new MimeBodyPart();
        messageBodyPart.setText(body, "utf-8", html ? "html" : "plain");
        multipart.addBodyPart(messageBodyPart);
    }

    if (attachments != null)
        for (NodeRef att : attachments) {
            messageBodyPart = new MimeBodyPart();
            String fileName = (String) nodeService.getProperty(att, AlvexContentModel.PROP_EMAIL_REAL_NAME);
            messageBodyPart
                    .setDataHandler(new DataHandler(new RepositoryDataSource(att, fileName, contentService)));
            messageBodyPart.setFileName(fileName);
            multipart.addBodyPart(messageBodyPart);
        }

    msg.setContent(multipart);

    SMTPTransport t = (SMTPTransport) session.getTransport(provider.getOutgoingProto());
    t.connect(config.getUsername(), config.getPassword());
    t.sendMessage(msg, msg.getAllRecipients());
    t.close();
}

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 {/*from w w  w  .  j av  a2  s.c  om*/

        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:it.eng.spagobi.tools.scheduler.jobs.CopyOfExecuteBIDocumentJob.java

private void sendToDl(DispatchContext sInfo, BIObject biobj, byte[] response, String retCT, String fileExt,
        String toBeAppendedToName, String toBeAppendedToDescription) {
    logger.debug("IN");
    try {//from ww w.java 2 s  .com

        String smtphost = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.smtphost");
        if ((smtphost == null) || smtphost.trim().equals(""))
            throw new Exception("Smtp host not configured");
        String from = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.from");
        if ((from == null) || from.trim().equals(""))
            from = "spagobi.scheduler@eng.it";
        String user = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.user");
        if ((user == null) || user.trim().equals(""))
            throw new Exception("Smtp user not configured");
        String pass = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.password");
        if ((pass == null) || pass.trim().equals(""))
            throw new Exception("Smtp password not configured");

        String mailTos = "";
        List dlIds = sInfo.getDlIds();
        Iterator it = dlIds.iterator();
        while (it.hasNext()) {

            Integer dlId = (Integer) it.next();
            DistributionList dl = DAOFactory.getDistributionListDAO().loadDistributionListById(dlId);

            List emails = new ArrayList();
            emails = dl.getEmails();
            Iterator j = emails.iterator();
            while (j.hasNext()) {
                Email e = (Email) j.next();
                String email = e.getEmail();
                String userTemp = e.getUserId();
                IEngUserProfile userProfile = GeneralUtilities.createNewUserProfile(userTemp);
                if (ObjectsAccessVerifier.canSee(biobj, userProfile)) {
                    if (j.hasNext()) {
                        mailTos = mailTos + email + ",";
                    } else {
                        mailTos = mailTos + email;
                    }
                }

            }
        }

        if ((mailTos == null) || mailTos.trim().equals("")) {
            throw new Exception("No recipient address found");
        }

        String[] recipients = mailTos.split(",");
        //Set the host smtp address
        Properties props = new Properties();
        props.put("mail.smtp.host", smtphost);
        props.put("mail.smtp.auth", "true");
        // create autheticator object
        Authenticator auth = new SMTPAuthenticator(user, pass);
        // open session
        Session session = Session.getDefaultInstance(props, auth);
        // create a message
        Message msg = new MimeMessage(session);
        // set the from and to address
        InternetAddress addressFrom = new InternetAddress(from);
        msg.setFrom(addressFrom);
        InternetAddress[] addressTo = new InternetAddress[recipients.length];
        for (int i = 0; i < recipients.length; i++) {
            addressTo[i] = new InternetAddress(recipients[i]);
        }
        msg.setRecipients(Message.RecipientType.TO, addressTo);
        // Setting the Subject and Content Type
        IMessageBuilder msgBuilder = MessageBuilderFactory.getMessageBuilder();
        String subject = biobj.getName() + toBeAppendedToName;
        msg.setSubject(subject);
        // create and fill the first message part
        //MimeBodyPart mbp1 = new MimeBodyPart();
        //mbp1.setText(mailTxt);
        // create the second message part
        MimeBodyPart mbp2 = new MimeBodyPart();
        // attach the file to the message
        SchedulerDataSource sds = new SchedulerDataSource(response, retCT,
                biobj.getName() + toBeAppendedToName + fileExt);
        mbp2.setDataHandler(new DataHandler(sds));
        mbp2.setFileName(sds.getName());
        // create the Multipart and add its parts to it
        Multipart mp = new MimeMultipart();
        //mp.addBodyPart(mbp1);
        mp.addBodyPart(mbp2);
        // add the Multipart to the message
        msg.setContent(mp);
        // send message
        Transport.send(msg);
    } catch (Exception e) {
        logger.error("Error while sending schedule result mail", e);
    } finally {
        logger.debug("OUT");
    }
}

From source file:it.eng.spagobi.tools.scheduler.jobs.CopyOfExecuteBIDocumentJob.java

private void sendMail(DispatchContext sInfo, BIObject biobj, Map parMap, byte[] response, String retCT,
        String fileExt, IDataStore dataStore, String toBeAppendedToName, String toBeAppendedToDescription) {
    logger.debug("IN");
    try {/*from   w ww.java  2 s  . c  o m*/

        String smtphost = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.smtphost");
        String smtpport = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.smtpport");
        int smptPort = 25;

        if ((smtphost == null) || smtphost.trim().equals(""))
            throw new Exception("Smtp host not configured");
        if ((smtpport == null) || smtpport.trim().equals("")) {
            throw new Exception("Smtp host not configured");
        } else {
            smptPort = Integer.parseInt(smtpport);
        }

        String from = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.from");
        if ((from == null) || from.trim().equals(""))
            from = "spagobi.scheduler@eng.it";
        String user = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.user");
        if ((user == null) || user.trim().equals("")) {
            logger.debug("Smtp user not configured");
            user = null;
        }
        //   throw new Exception("Smtp user not configured");
        String pass = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.password");
        if ((pass == null) || pass.trim().equals("")) {
            logger.debug("Smtp password not configured");
        }
        //   throw new Exception("Smtp password not configured");

        String mailSubj = sInfo.getMailSubj();
        mailSubj = StringUtilities.substituteParametersInString(mailSubj, parMap, null, false);

        String mailTxt = sInfo.getMailTxt();

        String[] recipients = findRecipients(sInfo, biobj, dataStore);
        if (recipients == null || recipients.length == 0) {
            logger.error("No recipients found for email sending!!!");
            return;
        }

        //Set the host smtp address
        Properties props = new Properties();
        props.put("mail.smtp.host", smtphost);
        props.put("mail.smtp.port", smptPort);

        // open session
        Session session = null;

        // create autheticator object
        Authenticator auth = null;
        if (user != null) {
            auth = new SMTPAuthenticator(user, pass);
            props.put("mail.smtp.auth", "true");
            session = Session.getDefaultInstance(props, auth);
            logger.error("Session.getDefaultInstance(props, auth)");
        } else {
            session = Session.getDefaultInstance(props);
            logger.error("Session.getDefaultInstance(props)");
        }

        // create a message
        Message msg = new MimeMessage(session);
        // set the from and to address
        InternetAddress addressFrom = new InternetAddress(from);
        msg.setFrom(addressFrom);
        InternetAddress[] addressTo = new InternetAddress[recipients.length];
        for (int i = 0; i < recipients.length; i++) {
            addressTo[i] = new InternetAddress(recipients[i]);
        }
        msg.setRecipients(Message.RecipientType.TO, addressTo);
        // Setting the Subject and Content Type
        String subject = mailSubj + " " + biobj.getName() + toBeAppendedToName;
        msg.setSubject(subject);
        // create and fill the first message part
        MimeBodyPart mbp1 = new MimeBodyPart();
        mbp1.setText(mailTxt + "\n" + toBeAppendedToDescription);
        // create the second message part
        MimeBodyPart mbp2 = new MimeBodyPart();
        // attach the file to the message

        SchedulerDataSource sds = new SchedulerDataSource(response, retCT,
                biobj.getName() + toBeAppendedToName + fileExt);
        mbp2.setDataHandler(new DataHandler(sds));
        mbp2.setFileName(sds.getName());
        // create the Multipart and add its parts to it
        Multipart mp = new MimeMultipart();
        mp.addBodyPart(mbp1);
        mp.addBodyPart(mbp2);
        // add the Multipart to the message
        msg.setContent(mp);
        // send message
        Transport.send(msg);
    } catch (Exception e) {
        logger.error("Error while sending schedule result mail", e);
    } finally {
        logger.debug("OUT");
    }
}