Example usage for javax.mail.internet MimeBodyPart setDataHandler

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

Introduction

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

Prototype

@Override
public void setDataHandler(DataHandler dh) throws MessagingException 

Source Link

Document

This method provides the mechanism to set this body part's content.

Usage

From source file:Implement.Service.AdminServiceImpl.java

@Override
public boolean sendPackageApprovedEmail(PackageApprovedEmailData emailData) throws MessagingException {
    String path = System.getProperty("catalina.base");
    MimeBodyPart logo = new MimeBodyPart();
    // attach the file to the message
    DataSource source = new FileDataSource(new File(path + "/webapps/Images/Email/logoIcon.png"));
    logo.setDataHandler(new DataHandler(source));
    logo.setFileName("logoIcon.png");
    logo.setDisposition(MimeBodyPart.INLINE);
    logo.setHeader("Content-ID", "<logo_Icon>"); // cid:image_cid

    MimeBodyPart facebook = new MimeBodyPart();
    // attach the file to the message
    source = new FileDataSource(new File(path + "/webapps/Images/Email/facebookIcon.png"));
    facebook.setDataHandler(new DataHandler(source));
    facebook.setFileName("facebookIcon.png");
    facebook.setDisposition(MimeBodyPart.INLINE);
    facebook.setHeader("Content-ID", "<fb_Icon>"); // cid:image_cid

    MimeBodyPart twitter = new MimeBodyPart();
    // attach the file to the message
    source = new FileDataSource(new File(path + "/webapps/Images/Email/twitterIcon.png"));
    twitter.setDataHandler(new DataHandler(source));
    twitter.setFileName("twitterIcon.png");
    twitter.setDisposition(MimeBodyPart.INLINE);
    twitter.setHeader("Content-ID", "<twitter_Icon>"); // cid:image_cid

    MimeBodyPart insta = new MimeBodyPart();
    // attach the file to the message
    source = new FileDataSource(new File(path + "/webapps/Images/Email/instaIcon.png"));
    insta.setDataHandler(new DataHandler(source));
    insta.setFileName("instaIcon.png");
    insta.setDisposition(MimeBodyPart.INLINE);
    insta.setHeader("Content-ID", "<insta_Icon>"); // cid:image_cid

    MimeBodyPart youtube = new MimeBodyPart();
    // attach the file to the message
    source = new FileDataSource(new File(path + "/webapps/Images/Email/youtubeIcon.png"));
    youtube.setDataHandler(new DataHandler(source));
    youtube.setFileName("youtubeIcon.png");
    youtube.setDisposition(MimeBodyPart.INLINE);
    youtube.setHeader("Content-ID", "<yt_Icon>"); // cid:image_cid

    MimeBodyPart pinterest = new MimeBodyPart();
    // attach the file to the message
    source = new FileDataSource(new File(path + "/webapps/Images/Email/pinterestIcon.png"));
    pinterest.setDataHandler(new DataHandler(source));
    pinterest.setFileName("pinterestIcon.png");
    pinterest.setDisposition(MimeBodyPart.INLINE);
    pinterest.setHeader("Content-ID", "<pin_Icon>"); // cid:image_cid

    String content = "<div style=' width: 507px;background-color: #f2f2f4;'>"
            + "    <div style='padding: 30px 0;text-align: center; color: #fff; background-color: #ff514e;font-size: 30px;font-weight: bold;'>"
            + "        <img style=' text-align:center;' width=57 height=57 src='cid:logo_Icon'/>"
            + "        <p style='margin:25px 0px 0px 0px;'> Package Approved! </p>" + "    </div>"
            + "    <div style=' padding: 50px;margin-bottom: 20px;'>" + "        <div id='email-form'>"
            + "            <div style='margin-bottom: 20px'>" + "                Hi " + emailData.getLastName()
            + " ,<br/>" + "                Your package " + emailData.getLastestPackageName()
            + " has been approved" + "            </div>" + "            <div style='margin-bottom: 20px'>"
            + "                Thanks,<br/>" + "                Youtripper team\n" + "            </div>"
            + "        </div>" + "        <div style='border-top: solid 1px #c4c5cc;text-align:center;'>"
            + "            <p style='text-align: center; color: #3b3e53;margin-top: 10px;margin-bottom: 0px;font-size: 10px;'>Sent from Youtripper.com</p>"
            + "            <div>"
            + "                <a href='https://www.facebook.com/youtrippers/'><img style='margin:10px;' src='cid:fb_Icon' alt=''/></a>"
            + "                <a href='https://twitter.com/youtrippers'><img style='margin:10px;' src='cid:twitter_Icon' alt=''/></a>"
            + "                <a href='https://www.instagram.com/youtrippers/'><img style='margin:10px;' src='cid:insta_Icon' alt=''/></a>"
            + "                <a href='https://www.youtube.com/channel/UCtd4xd_SSjRR9Egug7tXIWA'><img style='margin:10px;' src='cid:yt_Icon' alt=''/></a>"
            + "                <a href='https://www.pinterest.com/youtrippers/'><img style='margin:10px;' src='cid:pin_Icon' alt=''/></a>"
            + "            </div>"
            + "            <p>Youtripper Ltd., 56 Soi Seri Villa, Srinakarin Rd., Nongbon,"
            + "                <br>Pravet, Bangkok, Thailand 10250</p>" + "        </div>" + "    </div>"
            + "</div>";

    MimeBodyPart mbp1 = new MimeBodyPart();
    mbp1.setText(content, "US-ASCII", "html");

    Multipart mp = new MimeMultipart("related");
    mp.addBodyPart(mbp1);/*  w w w  .  ja  va2 s  .  c  o  m*/
    mp.addBodyPart(logo);
    mp.addBodyPart(facebook);
    mp.addBodyPart(twitter);
    mp.addBodyPart(insta);
    mp.addBodyPart(youtube);
    mp.addBodyPart(pinterest);

    final String username = "noreply@youtripper.com";
    final String password = "Tripper190515";
    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", "mail.youtripper.com");

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

    Message message = new MimeMessage(session);
    message.setFrom(new InternetAddress("noreply@youtripper.com"));
    message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(emailData.getEmail()));
    message.setSubject("Package Approved!");
    message.setContent(mp);
    message.saveChanges();
    Transport.send(message);
    return true;
}

From source file:de.mendelson.comm.as2.message.AS2MessageCreation.java

/**Compresses the payload using the ZLIB algorithm
 *//*from   w  w w.j a v a2s  .  co m*/
private MimeBodyPart compressPayload(Partner receiver, byte[] data, String contentType)
        throws SMIMEException, MessagingException {
    MimeBodyPart bodyPart = new MimeBodyPart();
    bodyPart.setDataHandler(new DataHandler(new ByteArrayDataSource(data, contentType)));
    bodyPart.addHeader("Content-Type", contentType);
    if (receiver.getContentTransferEncoding() == AS2Message.CONTENT_TRANSFER_ENCODING_BASE64) {
        bodyPart.addHeader("Content-Transfer-Encoding", "base64");
    } else {
        bodyPart.addHeader("Content-Transfer-Encoding", "binary");
    }
    SMIMECompressedGenerator generator = new SMIMECompressedGenerator();
    if (receiver.getContentTransferEncoding() == AS2Message.CONTENT_TRANSFER_ENCODING_BASE64) {
        generator.setContentTransferEncoding("base64");
    } else {
        generator.setContentTransferEncoding("binary");
    }
    return (generator.generate(bodyPart, SMIMECompressedGenerator.ZLIB));
}

From source file:com.photon.phresco.util.Utility.java

public static void sendTemplateEmail(String[] toAddr, String fromAddr, String user, String subject, String body,
        String username, String password, String host, String screen, String build) throws PhrescoException {

    List<String> lists = Arrays.asList(toAddr);
    if (fromAddr == null) {
        fromAddr = "phresco.do.not.reply@gmail.com";
        username = "phresco.do.not.reply@gmail.com";
        password = "phresco123";
    }//  w ww . j ava 2 s .  c  o  m
    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.port", "587");
    Session session = Session.getDefaultInstance(props, new LoginAuthenticator(username, password));
    try {
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(fromAddr));
        List<Address> emailsList = getEmailsList(lists);
        Address[] dsf = new Address[emailsList.size()];
        message.setRecipients(Message.RecipientType.BCC, emailsList.toArray(dsf));
        message.setSubject(subject);
        DataSource source = new FileDataSource(body);
        BodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName("Error.txt");
        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(messageBodyPart);
        MimeBodyPart messageBodyPart2 = new MimeBodyPart();
        DataSource source2 = new FileDataSource(screen);
        messageBodyPart2.setDataHandler(new DataHandler(source2));
        messageBodyPart2.setFileName("Error.jpg");
        multipart.addBodyPart(messageBodyPart2);
        MimeBodyPart mainPart = new MimeBodyPart();
        String content = "<b>Phresco framework error report<br><br>User Name:&nbsp;&nbsp;" + user
                + "<br> Email Address:&nbsp;&nbsp;" + fromAddr + "<br>Build No:&nbsp;&nbsp;" + build;
        mainPart.setContent(content, "text/html");
        multipart.addBodyPart(mainPart);
        message.setContent(multipart);
        Transport.send(message);
    } catch (MessagingException e) {
        throw new PhrescoException(e);
    }
}

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

private MimeBodyPart createAttachmentPart(Attachment attachment) {
    try {//w  w w.j  a  v  a  2s.c  om
        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:com.autentia.tnt.mail.DefaultMailService.java

public void sendOutputStreams(String to, String subject, String text, Map<InputStream, String> attachments)
        throws MessagingException {
    Transport t = null;/*from ww w .jav a 2 s.  c  om*/

    try {
        MimeMessage message = new MimeMessage(session);

        t = session.getTransport("smtp");

        message.setFrom(new InternetAddress(configurationUtil.getMailUsername()));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
        message.setSubject(subject);
        message.setSentDate(new Date());
        if (attachments == null || attachments.size() < 1) {
            message.setText(text);
        } else {
            // create the message part 
            MimeBodyPart messageBodyPart = new MimeBodyPart();
            messageBodyPart.setText(text);
            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(messageBodyPart);
            try {
                for (InputStream attachment : attachments.keySet()) {
                    messageBodyPart = new MimeBodyPart();
                    DataSource source = new ByteArrayDataSource(attachment, "application/octet-stream");

                    messageBodyPart.setDataHandler(new DataHandler(source));
                    messageBodyPart.setFileName(attachments.get(attachment)); //NOSONAR 
                    multipart.addBodyPart(messageBodyPart); //Se emplea keyset y no valueset porque se emplea tanto la key como el val
                }
            } catch (IOException e) {
                throw new MessagingException("cannot add an attachment to mail", e);
            }
            message.setContent(multipart);
        }

        t.connect(configurationUtil.getMailUsername(), configurationUtil.getMailPassword());

        t.sendMessage(message, message.getAllRecipients());
    } finally {
        if (t != null) {
            t.close();
        }
    }

}

From source file:com.eviware.soapui.impl.wsdl.submit.filters.HttpRequestFilter.java

protected void initRootPart(HttpRequestInterface<?> wsdlRequest, String requestContent, MimeMultipart mp)
        throws MessagingException {
    MimeBodyPart rootPart = new PreencodedMimeBodyPart("8bit");
    // rootPart.setContentID( AttachmentUtils.ROOTPART_SOAPUI_ORG );
    mp.addBodyPart(rootPart, 0);//from  w  w  w  .j  a  v  a  2  s.c  o  m

    DataHandler dataHandler = new DataHandler(new RestRequestDataSource(wsdlRequest, requestContent));
    rootPart.setDataHandler(dataHandler);
}

From source file:rescustomerservices.GmailQuickstart.java

/**
 * Create a MimeMessage using the parameters provided.
 *
 * @param to Email address of the receiver.
 * @param from Email address of the sender, the mailbox account.
 * @param subject Subject of the email./*from   w  ww . j a va  2  s  .c  o  m*/
 * @param bodyText Body text of the email.
 * @param fileDir Path to the directory containing attachment.
 * @param filename Name of file to be attached.
 * @return MimeMessage to be used to send email.
 * @throws MessagingException
 */
public MimeMessage createEmailWithAttachment(String to, String from, String subject, String bodyText,
        String fileDir, String filename) throws MessagingException, IOException {
    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);

    MimeMessage email = new MimeMessage(session);
    InternetAddress tAddress = new InternetAddress(to);
    InternetAddress fAddress = new InternetAddress(from);

    email.setFrom(fAddress);
    email.addRecipient(javax.mail.Message.RecipientType.TO, tAddress);
    email.setSubject(subject);

    MimeBodyPart mimeBodyPart = new MimeBodyPart();
    mimeBodyPart.setContent(bodyText, "text/plain");
    mimeBodyPart.setHeader("Content-Type", "text/plain; charset=\"UTF-8\"");

    Multipart multipart = new MimeMultipart();
    multipart.addBodyPart(mimeBodyPart);

    mimeBodyPart = new MimeBodyPart();
    DataSource source = new FileDataSource(fileDir + filename);

    mimeBodyPart.setDataHandler(new DataHandler(source));
    mimeBodyPart.setFileName(filename);
    String contentType = Files.probeContentType(FileSystems.getDefault().getPath(fileDir, filename));
    mimeBodyPart.setHeader("Content-Type", contentType + "; name=\"" + filename + "\"");
    mimeBodyPart.setHeader("Content-Transfer-Encoding", "base64");

    multipart.addBodyPart(mimeBodyPart);

    email.setContent(multipart);

    return email;
}

From source file:org.pentaho.platform.plugin.action.builtin.EmailComponent.java

@Override
public boolean executeAction() {
    EmailAction emailAction = (EmailAction) getActionDefinition();

    String messagePlain = emailAction.getMessagePlain().getStringValue();
    String messageHtml = emailAction.getMessageHtml().getStringValue();
    String subject = emailAction.getSubject().getStringValue();
    String to = emailAction.getTo().getStringValue();
    String cc = emailAction.getCc().getStringValue();
    String bcc = emailAction.getBcc().getStringValue();
    String from = emailAction.getFrom().getStringValue(defaultFrom);
    if (from.trim().length() == 0) {
        from = defaultFrom;//from ww w  .j  a  v  a2 s .com
    }

    /*
     * if( context.getInputNames().contains( "attach" ) ) { //$NON-NLS-1$ Object attachParameter =
     * context.getInputParameter( "attach" ).getValue(); //$NON-NLS-1$ // We have a list of attachments, each element of
     * the list is the name of the parameter containing the attachment // Use the parameter filename portion as the
     * attachment name. if ( attachParameter instanceof String ) { String attachName = context.getInputParameter(
     * "attach-name" ).getStringValue(); //$NON-NLS-1$ AttachStruct attachData = getAttachData( context,
     * (String)attachParameter, attachName ); if ( attachData != null ) { attachments.add( attachData ); } } else if (
     * attachParameter instanceof List ) { for ( int i = 0; i < ((List)attachParameter).size(); ++i ) { AttachStruct
     * attachData = getAttachData( context, ((List)attachParameter).get( i ).toString(), null ); if ( attachData != null
     * ) { attachments.add( attachData ); } } } else if ( attachParameter instanceof Map ) { for ( Iterator it =
     * ((Map)attachParameter).entrySet().iterator(); it.hasNext(); ) { Map.Entry entry = (Map.Entry)it.next();
     * AttachStruct attachData = getAttachData( context, (String)entry.getValue(), (String)entry.getKey() ); if (
     * attachData != null ) { attachments.add( attachData ); } } } }
     * 
     * int maxSize = Integer.MAX_VALUE; try { maxSize = new Integer( props.getProperty( "mail.max.attach.size" )
     * ).intValue(); } catch( Throwable t ) { //ignore if not set to a valid value }
     * 
     * if ( totalAttachLength > maxSize ) { // Sort them in order TreeMap tm = new TreeMap(); for( int idx=0;
     * idx<attachments.size(); idx++ ) { // tm.put( new Integer( )) } }
     */

    if (ComponentBase.debug) {
        debug(Messages.getInstance().getString("Email.DEBUG_TO_FROM", to, from)); //$NON-NLS-1$
        debug(Messages.getInstance().getString("Email.DEBUG_CC_BCC", cc, bcc)); //$NON-NLS-1$
        debug(Messages.getInstance().getString("Email.DEBUG_SUBJECT", subject)); //$NON-NLS-1$
        debug(Messages.getInstance().getString("Email.DEBUG_PLAIN_MESSAGE", messagePlain)); //$NON-NLS-1$
        debug(Messages.getInstance().getString("Email.DEBUG_HTML_MESSAGE", messageHtml)); //$NON-NLS-1$
    }

    if ((to == null) || (to.trim().length() == 0)) {

        // Get the output stream that the feedback is going into
        OutputStream feedbackStream = getFeedbackOutputStream();
        if (feedbackStream != null) {
            createFeedbackParameter("to", Messages.getInstance().getString("Email.USER_ENTER_EMAIL_ADDRESS"), //$NON-NLS-1$//$NON-NLS-2$
                    "", "", true); //$NON-NLS-1$ //$NON-NLS-2$
            setFeedbackMimeType("text/html"); //$NON-NLS-1$
            return true;
        } else {
            return false;
        }
    }
    if (subject == null) {
        error(Messages.getInstance().getErrorString("Email.ERROR_0005_NULL_SUBJECT", getActionName())); //$NON-NLS-1$
        return false;
    }
    if ((messagePlain == null) && (messageHtml == null)) {
        error(Messages.getInstance().getErrorString("Email.ERROR_0006_NULL_BODY", getActionName())); //$NON-NLS-1$
        return false;
    }

    if (getRuntimeContext().isPromptPending()) {
        return true;
    }

    try {
        Properties props = new Properties();
        final IEmailService service = PentahoSystem.get(IEmailService.class, "IEmailService",
                PentahoSessionHolder.getSession());
        props.put("mail.smtp.host", service.getEmailConfig().getSmtpHost());
        props.put("mail.smtp.port", ObjectUtils.toString(service.getEmailConfig().getSmtpPort()));
        props.put("mail.transport.protocol", service.getEmailConfig().getSmtpProtocol());
        props.put("mail.smtp.starttls.enable", ObjectUtils.toString(service.getEmailConfig().isUseStartTls()));
        props.put("mail.smtp.auth", ObjectUtils.toString(service.getEmailConfig().isAuthenticate()));
        props.put("mail.smtp.ssl", ObjectUtils.toString(service.getEmailConfig().isUseSsl()));
        props.put("mail.smtp.quitwait", ObjectUtils.toString(service.getEmailConfig().isSmtpQuitWait()));
        props.put("mail.from.default", service.getEmailConfig().getDefaultFrom());
        String fromName = service.getEmailConfig().getFromName();
        if (StringUtils.isEmpty(fromName)) {
            fromName = Messages.getInstance().getString("schedulerEmailFromName");
        }
        props.put("mail.from.name", fromName);
        props.put("mail.debug", ObjectUtils.toString(service.getEmailConfig().isDebug()));

        Session session;
        if (service.getEmailConfig().isAuthenticate()) {
            props.put("mail.userid", service.getEmailConfig().getUserId());
            props.put("mail.password", service.getEmailConfig().getPassword());
            Authenticator authenticator = new EmailAuthenticator();
            session = Session.getInstance(props, authenticator);
        } else {
            session = Session.getInstance(props);
        }

        // debugging is on if either component (xaction) or email config debug is on
        if (service.getEmailConfig().isDebug() || ComponentBase.debug) {
            session.setDebug(true);
        }

        // construct the message
        MimeMessage msg = new MimeMessage(session);
        if (from != null) {
            msg.setFrom(new InternetAddress(from));
        } else {
            // There should be no way to get here
            error(Messages.getInstance().getString("Email.ERROR_0012_FROM_NOT_DEFINED")); //$NON-NLS-1$
        }

        if ((to != null) && (to.trim().length() > 0)) {
            msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
        }
        if ((cc != null) && (cc.trim().length() > 0)) {
            msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false));
        }
        if ((bcc != null) && (bcc.trim().length() > 0)) {
            msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false));
        }

        if (subject != null) {
            msg.setSubject(subject, LocaleHelper.getSystemEncoding());
        }

        EmailAttachment[] emailAttachments = emailAction.getAttachments();
        if ((messagePlain != null) && (messageHtml == null) && (emailAttachments.length == 0)) {
            msg.setText(messagePlain, LocaleHelper.getSystemEncoding());
        } else if (emailAttachments.length == 0) {
            if (messagePlain != null) {
                msg.setContent(messagePlain, "text/plain; charset=" + LocaleHelper.getSystemEncoding()); //$NON-NLS-1$          
            }
            if (messageHtml != null) {
                msg.setContent(messageHtml, "text/html; charset=" + LocaleHelper.getSystemEncoding()); //$NON-NLS-1$
            }
        } else {
            // need to create a multi-part message...
            // create the Multipart and add its parts to it
            Multipart multipart = new MimeMultipart();
            // create and fill the first message part
            if (messageHtml != null) {
                // create and fill the first message part
                MimeBodyPart htmlBodyPart = new MimeBodyPart();
                htmlBodyPart.setContent(messageHtml, "text/html; charset=" + LocaleHelper.getSystemEncoding()); //$NON-NLS-1$
                multipart.addBodyPart(htmlBodyPart);
            }

            if (messagePlain != null) {
                MimeBodyPart textBodyPart = new MimeBodyPart();
                textBodyPart.setContent(messagePlain,
                        "text/plain; charset=" + LocaleHelper.getSystemEncoding()); //$NON-NLS-1$
                multipart.addBodyPart(textBodyPart);
            }

            for (EmailAttachment element : emailAttachments) {
                IPentahoStreamSource source = element.getContent();
                if (source == null) {
                    error(Messages.getInstance().getErrorString("Email.ERROR_0015_ATTACHMENT_FAILED")); //$NON-NLS-1$
                    return false;
                }
                DataSource dataSource = new ActivationHelper.PentahoStreamSourceWrapper(source);
                String attachmentName = element.getName();
                if (ComponentBase.debug) {
                    debug(Messages.getInstance().getString("Email.DEBUG_ADDING_ATTACHMENT", attachmentName)); //$NON-NLS-1$
                }

                // create the second message part
                MimeBodyPart attachmentBodyPart = new MimeBodyPart();

                // attach the file to the message
                attachmentBodyPart.setDataHandler(new DataHandler(dataSource));
                attachmentBodyPart.setFileName(attachmentName);
                if (ComponentBase.debug) {
                    debug(Messages.getInstance().getString("Email.DEBUG_ATTACHMENT_SOURCE", //$NON-NLS-1$
                            dataSource.getName()));
                }
                multipart.addBodyPart(attachmentBodyPart);
            }

            // add the Multipart to the message
            msg.setContent(multipart);
        }

        msg.setHeader("X-Mailer", EmailComponent.MAILER); //$NON-NLS-1$
        msg.setSentDate(new Date());

        Transport.send(msg);

        if (ComponentBase.debug) {
            debug(Messages.getInstance().getString("Email.DEBUG_EMAIL_SUCCESS")); //$NON-NLS-1$
        }
        return true;
        // TODO: persist the content set for a while...
    } catch (SendFailedException e) {
        error(Messages.getInstance().getErrorString("Email.ERROR_0011_SEND_FAILED", to), e); //$NON-NLS-1$
        /*
         * Exception ne; MessagingException sfe = e; while ((ne = sfe.getNextException()) != null && ne instanceof
         * MessagingException) { sfe = (MessagingException) ne;
         * error(Messages.getInstance().getErrorString("Email.ERROR_0011_SEND_FAILED", sfe.toString()), sfe);
         * //$NON-NLS-1$ }
         */

    } catch (AuthenticationFailedException e) {
        error(Messages.getInstance().getString("Email.ERROR_0014_AUTHENTICATION_FAILED", to), e); //$NON-NLS-1$
    } catch (Throwable e) {
        error(Messages.getInstance().getErrorString("Email.ERROR_0011_SEND_FAILED", to), e); //$NON-NLS-1$
    }
    return false;
}

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

public boolean dispatch(BIObject document, byte[] executionOutput) {

    String contentType;/*from ww  w . jav a2 s. c  om*/
    String fileExtension;
    String nameSuffix;
    JobExecutionContext jobExecutionContext;

    logger.debug("IN");

    try {

        contentType = dispatchContext.getContentType();
        fileExtension = dispatchContext.getFileExtension();
        nameSuffix = dispatchContext.getNameSuffix();
        jobExecutionContext = dispatchContext.getJobExecutionContext();

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

        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);

        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";

        int smptPort = 25;

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

        String user = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.user");
        String pass = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.password");

        /*
        if( (user==null) || user.trim().equals(""))
           throw new Exception("Smtp user not configured");
                
        if( (pass==null) || pass.trim().equals(""))
           throw new Exception("Smtp password not configured");
        */

        String mailTos = "";
        List dlIds = dispatchContext.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(document, 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.port", Integer.toString(smptPort));

        Session session = null;

        if (StringUtilities.isEmpty(user) || StringUtilities.isEmpty(pass)) {
            props.put("mail.smtp.auth", "false");
            session = Session.getInstance(props);
            logger.debug("Connecting to mail server without authentication");
        } else {
            props.put("mail.smtp.auth", "true");
            Authenticator auth = new SMTPAuthenticator(user, pass);
            //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.getInstance(props, auth);
            logger.debug("Connecting to mail server with authentication");
        }

        // 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 = document.getName() + nameSuffix;
        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(executionOutput, contentType,
                document.getName() + 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);
        }

        if (jobExecutionContext.getNextFireTime() == null) {
            String triggername = jobExecutionContext.getTrigger().getName();
            dlIds = dispatchContext.getDlIds();
            it = dlIds.iterator();
            while (it.hasNext()) {
                Integer dlId = (Integer) it.next();
                DistributionList dl = DAOFactory.getDistributionListDAO().loadDistributionListById(dlId);
                DAOFactory.getDistributionListDAO().eraseDistributionListObjects(dl,
                        (document.getId()).intValue(), triggername);
            }
        }
    } catch (Exception e) {
        logger.error("Error while sending schedule result mail", e);
        return false;
    } finally {
        logger.debug("OUT");
    }

    return true;
}

From source file:com.szmslab.quickjavamail.send.MailSender.java

/**
 * MimeBodyPart????Content-Disposition: attachment
 *
 * @param file/*w w w .j a va2s.c  om*/
 *            
 * @return MimeBodyPartContent-Disposition: attachment?
 * @throws MessagingException
 * @throws UnsupportedEncodingException
 */
private MimeBodyPart createAttachmentPart(AttachmentFile file)
        throws MessagingException, UnsupportedEncodingException {
    MimeBodyPart attachmentPart = new MimeBodyPart();
    attachmentPart.setFileName(MimeUtility.encodeText(file.getFileName(), charset, null));
    attachmentPart.setDataHandler(new DataHandler(file.getDataSource()));
    attachmentPart.setDisposition(MimeBodyPart.ATTACHMENT);
    return attachmentPart;
}