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:org.openadaptor.auxil.connector.smtp.SMTPConnection.java

/**
 * Generate body of email. It will either be a mime multipart message or text. This is
 * determined by the <code>recordsAsAttachment</code> property.
 *
 * @param body//  www.j a  va2s.c om
 * @throws MessagingException
 */
public void generateMessageBody(String body) throws MessagingException {
    MimeBodyPart mbpPrefaceBody, mbpBody;
    MimeMultipart mmp;

    // Determine if records are to be send as an attachment
    if (recordsAsAttachment) {
        //Define mime parts
        mbpPrefaceBody = new MimeBodyPart();
        mbpPrefaceBody.setText(bodyPreface);
        mbpBody = new MimeBodyPart();
        if (mimeContentType != null && !(mimeContentType.length() == 0)) {
            mbpBody.setContent(body, mimeContentType);
        } else {
            mbpBody.setText(body);
        }
        //Create mime message
        mmp = new MimeMultipart();
        mmp.addBodyPart(mbpPrefaceBody);
        mmp.addBodyPart(mbpBody);
        message.setContent(mmp);
    } else if (mimeContentType != null && !(mimeContentType.length() == 0)) {
        message.setContent(bodyPreface + "\n\n" + body, mimeContentType);
    } else {
        message.setText(bodyPreface + "\n\n" + body);
    }
}

From source file:fsi_admin.JSmtpConn.java

@SuppressWarnings({ "rawtypes", "unchecked" })
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String ERROR = null, codErr = null;

    try {/* w ww . j  a  v  a  2  s  .c  om*/
        Properties parametros = new Properties();
        Vector archivos = new Vector();
        DiskFileUpload fu = new DiskFileUpload();
        List items = fu.parseRequest(request);
        Iterator iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            if (item.isFormField())
                parametros.put(item.getFieldName(), item.getString());
            else
                archivos.addElement(item);
        }

        if (parametros.getProperty("SERVER") == null || parametros.getProperty("DATABASE") == null
                || parametros.getProperty("USER") == null || parametros.getProperty("PASSWORD") == null
                || parametros.getProperty("BODY") == null || parametros.getProperty("MIMETYPE") == null
                || parametros.getProperty("SUBJECT") == null || parametros.getProperty("EMAIL") == null
                || parametros.getProperty("SOURCEMAIL") == null) {
            System.out.println("No recibi parametros de conexin antes del correo a enviar");
            ERROR = "ERROR: El servidor no recibi todos los parametros de conexion (SERVER,DATABASE,USER,PASSWORD) antes del correo a enviar";
            codErr = "3";
            ingresarRegistroFallido(request.getRemoteAddr(), request.getRemoteHost(),
                    parametros.getProperty("SERVER"), parametros.getProperty("USER"),
                    parametros.getProperty("PASSWORD"), request, ERROR, 3);
        }

        //Hasta aqui se han enviado todos los parametros ninguno nulo
        if (ERROR == null) {
            StringBuffer msj = new StringBuffer(), SMTPHOST = new StringBuffer(), SMTPPORT = new StringBuffer(),
                    SMTPUSR = new StringBuffer(), SMTPPASS = new StringBuffer();
            MutableBoolean COBRAR = new MutableBoolean(false);
            MutableDouble COSTO = new MutableDouble(0.0), SALDO = new MutableDouble(0.0);
            // Primero obtiene info del SMTP
            if (!obtenInfoSMTP(request.getRemoteAddr(), request.getRemoteHost(),
                    parametros.getProperty("SERVER"), parametros.getProperty("DATABASE"),
                    parametros.getProperty("USER"), parametros.getProperty("PASSWORD"), SMTPHOST, SMTPPORT,
                    SMTPUSR, SMTPPASS, msj, COSTO, SALDO, COBRAR)) {
                System.out.println("El usuario y contrasea de servicio estan mal");
                ERROR = msj.toString();
                codErr = "2";
                ingresarRegistroFallido(request.getRemoteAddr(), request.getRemoteHost(),
                        parametros.getProperty("SERVER"), parametros.getProperty("USER"),
                        parametros.getProperty("PASSWORD"), request, ERROR, 2);

            } else {
                if (COBRAR.booleanValue() && SALDO.doubleValue() < COSTO.doubleValue()) {
                    System.out.println("El servicio tiene un costo que no alcanza en el saldo");
                    ERROR = "El servicio SMTP tiene un costo que no alcanza en el saldo";
                    codErr = "2";
                    ingresarRegistroFallido(request.getRemoteAddr(), request.getRemoteHost(),
                            parametros.getProperty("SERVER"), parametros.getProperty("USER"),
                            parametros.getProperty("PASSWORD"), request, ERROR, 2);

                } else {
                    Properties props;

                    props = System.getProperties();
                    props.put("mail.transport.protocol", "smtp");
                    props.put("mail.smtp.port", Integer.parseInt(SMTPPORT.toString()));

                    // Set properties indicating that we want to use STARTTLS to encrypt the connection.
                    // The SMTP session will begin on an unencrypted connection, and then the client
                    // will issue a STARTTLS command to upgrade to an encrypted connection.
                    props.put("mail.smtp.auth", "true");
                    props.put("mail.smtp.starttls.enable", "true");
                    props.put("mail.smtp.starttls.required", "true");

                    // Create a Session object to represent a mail session with the specified properties. 
                    Session session = Session.getDefaultInstance(props);
                    MimeMessage mmsg = new MimeMessage(session);
                    BodyPart messagebodypart = new MimeBodyPart();
                    MimeMultipart multipart = new MimeMultipart();

                    if (!prepareMsg(parametros.getProperty("SOURCEMAIL"), parametros.getProperty("EMAIL"),
                            parametros.getProperty("SUBJECT"), parametros.getProperty("MIMETYPE"),
                            parametros.getProperty("BODY"), msj, props, session, mmsg, messagebodypart,
                            multipart)) {
                        System.out.println("No se permiti preparar el mensaje");
                        ERROR = msj.toString();
                        codErr = "3";
                        ingresarRegistroFallido(request.getRemoteAddr(), request.getRemoteHost(),
                                parametros.getProperty("SERVER"), parametros.getProperty("USER"),
                                parametros.getProperty("PASSWORD"), request, ERROR, 3);

                    } else {
                        if (!adjuntarArchivo(msj, messagebodypart, multipart, archivos)) {
                            System.out.println("No se permiti adjuntar archivos al mensaje");
                            ERROR = msj.toString();
                            codErr = "3";
                            ingresarRegistroFallido(request.getRemoteAddr(), request.getRemoteHost(),
                                    parametros.getProperty("SERVER"), parametros.getProperty("USER"),
                                    parametros.getProperty("PASSWORD"), request, ERROR, 3);

                        } else {
                            if (!sendMsg(SMTPHOST.toString(), SMTPUSR.toString(), SMTPPASS.toString(), msj,
                                    session, mmsg, multipart)) {
                                System.out.println("No se permiti enviar el mensaje");
                                ERROR = msj.toString();
                                codErr = "3";
                                ingresarRegistroFallido(request.getRemoteAddr(), request.getRemoteHost(),
                                        parametros.getProperty("SERVER"), parametros.getProperty("USER"),
                                        parametros.getProperty("PASSWORD"), request, ERROR, 3);
                            } else {
                                ingresarRegistroExitoso(parametros.getProperty("SERVER"),
                                        parametros.getProperty("DATABASE"), parametros.getProperty("SUBJECT"),
                                        COSTO, SALDO, COBRAR);

                                //Devuelve la respuesta al cliente
                                Element Correo = new Element("Correo");
                                Correo.setAttribute("Subject", parametros.getProperty("SUBJECT"));
                                Correo.setAttribute("MsjError", "");
                                Document Reporte = new Document(Correo);

                                Format format = Format.getPrettyFormat();
                                format.setEncoding("utf-8");
                                format.setTextMode(TextMode.NORMALIZE);
                                XMLOutputter xmlOutputter = new XMLOutputter(format);
                                ByteArrayOutputStream out = new ByteArrayOutputStream();
                                xmlOutputter.output(Reporte, out);

                                byte[] data = out.toByteArray();
                                ByteArrayInputStream istream = new ByteArrayInputStream(data);

                                String destino = "Correo.xml";
                                JBajarArchivo fd = new JBajarArchivo();
                                fd.doDownload(response, getServletConfig().getServletContext(), istream,
                                        "text/xml", data.length, destino);

                            }
                        }
                    }
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        ERROR = "ERROR DE EXCEPCION EN SERVIDOR PAC: " + e.getMessage();
    }

    //Genera el archivo XML de error para ser devuelto al Servidor
    if (ERROR != null) {
        Element SIGN_ERROR = new Element("SIGN_ERROR");
        SIGN_ERROR.setAttribute("CodError", codErr);
        SIGN_ERROR.setAttribute("MsjError", ERROR);
        Document Reporte = new Document(SIGN_ERROR);

        Format format = Format.getPrettyFormat();
        format.setEncoding("utf-8");
        format.setTextMode(TextMode.NORMALIZE);
        XMLOutputter xmlOutputter = new XMLOutputter(format);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        xmlOutputter.output(Reporte, out);

        byte[] data = out.toByteArray();
        ByteArrayInputStream istream = new ByteArrayInputStream(data);

        String destino = "SIGN_ERROR.xml";
        JBajarArchivo fd = new JBajarArchivo();
        fd.doDownload(response, getServletConfig().getServletContext(), istream, "text/xml", data.length,
                destino);

    }
}

From source file:com.ephesoft.dcma.mail.service.MailServiceImpl.java

@Override
public void sendMailWithPreviousMailContent(final MailMetaData mailMetaData, final String text,
        final Message previousMailMessage) {
    LOGGER.debug("Sending mail with content from previous mail(MailServiceImpl)");
    if (suppressMail) {
        return;/*from ww w  . j a va2  s  .  c o m*/
    }
    setMailProperties();
    MimeMessagePreparator messagePreparator = new MimeMessagePreparator() {

        public void prepare(MimeMessage mimeMessage) throws Exception {

            if (null != mailMetaData.getCcAddresses() && mailMetaData.getCcAddresses().size() > 0) {
                setAddressToMessage(RecipientType.CC, mimeMessage, mailMetaData.getCcAddresses());
            }
            if (null != mailMetaData.getBccAddresses() && mailMetaData.getBccAddresses().size() > 0) {
                setAddressToMessage(RecipientType.BCC, mimeMessage, mailMetaData.getBccAddresses());
            }
            if (null != mailMetaData.getToAddresses() && mailMetaData.getToAddresses().size() > 0) {
                setAddressToMessage(RecipientType.TO, mimeMessage, mailMetaData.getToAddresses());
            }

            if (null != mailMetaData.getFromAddress()) {
                mimeMessage.setFrom(new InternetAddress(new StringBuilder().append(mailMetaData.getFromName())
                        .append(MailConstants.LESS_SYMBOL).append(mailMetaData.getFromAddress())
                        .append(MailConstants.GREATER_SYMBOL).toString()));
            }

            if (null != mailMetaData.getSubject() && null != text) {
                mimeMessage.setSubject(mailMetaData.getSubject());
            }

            if (null != text) {
                mimeMessage.setText(text);
            }

            // Create your new message part
            BodyPart messageBodyPart = new MimeBodyPart();
            messageBodyPart.setText(EphesoftStringUtil.concatenate(text, ORIGINAL_MAIL_MESSAGE));

            // Create a multi-part to combine the parts
            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(messageBodyPart);

            // Create and fill part for the forwarded content
            messageBodyPart = new MimeBodyPart();
            messageBodyPart.setDataHandler(previousMailMessage.getDataHandler());

            // Add part to multi part
            multipart.addBodyPart(messageBodyPart);

            // Associate multi-part with message
            mimeMessage.setContent(multipart);

        }
    };
    try {
        mailSender.send(messagePreparator);
    } catch (MailException mailException) {
        LOGGER.error("Error while sending mail to configured mail account", mailException);
        throw new SendMailException(
                EphesoftStringUtil.concatenate("Error sending mail: ", mailMetaData.toString()), mailException);
    }
    LOGGER.info("mail sent successfully");
}

From source file:lucee.runtime.net.mail.HtmlEmailImpl.java

/**
 * @throws EmailException EmailException
 * @throws MessagingException MessagingException
 *//*from  ww  w.  ja va2  s . c  o  m*/
private void buildNoAttachments() throws MessagingException, EmailException {
    MimeMultipart container = this.getContainer();
    MimeMultipart subContainerHTML = new MimeMultipart("related");

    container.setSubType("alternative");

    BodyPart msgText = null;
    BodyPart msgHtml = null;

    if (!StringUtil.isEmpty(this.text)) {
        msgText = this.getPrimaryBodyPart();
        if (!StringUtil.isEmpty(this.charset)) {
            msgText.setContent(this.text, Email.TEXT_PLAIN + "; charset=" + this.charset);
        } else {
            msgText.setContent(this.text, Email.TEXT_PLAIN);
        }
    }

    if (!StringUtil.isEmpty(this.html)) {
        // if the txt part of the message was null, then the html part
        // will become the primary body part
        if (msgText == null) {
            msgHtml = getPrimaryBodyPart();
        } else {
            if (this.inlineImages.size() > 0) {
                msgHtml = new MimeBodyPart();
                subContainerHTML.addBodyPart(msgHtml);
            } else {
                msgHtml = new MimeBodyPart();
                container.addBodyPart(msgHtml, 1);
            }
        }

        if (!StringUtil.isEmpty(this.charset)) {
            msgHtml.setContent(this.html, Email.TEXT_HTML + "; charset=" + this.charset);
        } else {
            msgHtml.setContent(this.html, Email.TEXT_HTML);
        }

        Iterator iter = this.inlineImages.iterator();
        while (iter.hasNext()) {
            subContainerHTML.addBodyPart((BodyPart) iter.next());
        }

        if (this.inlineImages.size() > 0) {
            // add sub container to message
            this.addPart(subContainerHTML);
        }
    }
}

From source file:javamailclient.GmailAPI.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 static 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:za.co.jumpingbean.alfresco.repo.EmailDocumentsAction.java

public void addAttachement(final NodeRef nodeRef, MimeMultipart content, final Boolean convert)
        throws MessagingException {

    MappedByteBuffer buf;/*from w  ww  . ja v a  2  s.co m*/
    byte[] array = new byte[0];
    ContentReader reader = serviceRegistry.getContentService().getReader(nodeRef, ContentModel.PROP_CONTENT);
    String fileName = (String) nodeService.getProperty(nodeRef, ContentModel.PROP_NAME);
    String type = reader.getMimetype().split("/")[0];
    if (!type.equalsIgnoreCase("image") && !reader.getMimetype().equalsIgnoreCase(MimetypeMap.MIMETYPE_PDF)
            && convert) {
        ContentWriter writer = contentService.getTempWriter();
        writer.setMimetype(MimetypeMap.MIMETYPE_PDF);
        String srcMimeType = reader.getMimetype();
        //String srcMimeType = ((ContentData) nodeService.getProperty(nodeRef, ContentModel.PROP_CONTENT)).getMimetype();
        //String srcMimeType = this.getMimeTypeForFileName(fileName);
        ContentTransformer transformer = contentService.getTransformer(srcMimeType, MimetypeMap.MIMETYPE_PDF);
        if (transformer != null) {
            try {
                transformer.transform(reader, writer);
                reader = writer.getReader();
                fileName = fileName.substring(0, fileName.lastIndexOf('.'));
                fileName += ".pdf";
            } catch (ContentIOException ex) {
                logger.warn("could not transform content");
                logger.warn(ex);
                //need to refresh reader as the transformer failing closes the reader
                reader = serviceRegistry.getContentService().getReader(nodeRef, ContentModel.PROP_CONTENT);
            }
        }
    }
    try {
        buf = reader.getFileChannel().map(FileChannel.MapMode.READ_ONLY, 0, reader.getSize());
        if (reader.getSize() <= Integer.MAX_VALUE) {
            array = new byte[(int) reader.getSize()];
            buf.get(array);
        }
    } catch (IOException ex) {
        logger.error("There was an error reading file into memory.");
        logger.error(ex);
        array = new byte[0];
    }

    ByteArrayDataSource ds = new ByteArrayDataSource(array, reader.getMimetype());
    MimeBodyPart attachment = new MimeBodyPart();
    attachment.setFileName(fileName);
    attachment.setDataHandler(new DataHandler(ds));
    content.addBodyPart(attachment);
}

From source file:org.pentaho.platform.scheduler2.email.Emailer.java

public boolean send() {
    String from = props.getProperty("mail.from.default");
    String fromName = props.getProperty("mail.from.name");
    String to = props.getProperty("to");
    String cc = props.getProperty("cc");
    String bcc = props.getProperty("bcc");
    boolean authenticate = "true".equalsIgnoreCase(props.getProperty("mail.smtp.auth"));
    String subject = props.getProperty("subject");
    String body = props.getProperty("body");

    logger.info("Going to send an email to " + to + " from " + from + " with the subject '" + subject
            + "' and the body " + body);

    try {/* ww  w .  j a  v a 2s  .  co  m*/
        // Get a Session object
        Session session;

        if (authenticate) {
            session = Session.getInstance(props, authenticator);
        } else {
            session = Session.getInstance(props);
        }

        // if debugging is not set in the email config file, then default to false
        if (!props.containsKey("mail.debug")) { //$NON-NLS-1$
            session.setDebug(false);
        }

        // construct the message
        MimeMessage msg = new MimeMessage(session);
        Multipart multipart = new MimeMultipart();

        if (from != null) {
            msg.setFrom(new InternetAddress(from, fromName));
        } else {
            // There should be no way to get here
            logger.error("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());
        }

        if (attachment == null) {
            logger.error("Email.ERROR_0015_ATTACHMENT_FAILED"); //$NON-NLS-1$
            return false;
        }

        ByteArrayDataSource dataSource = new ByteArrayDataSource(attachment, attachmentMimeType);

        if (body != null) {
            MimeBodyPart bodyMessagePart = new MimeBodyPart();
            bodyMessagePart.setText(body, LocaleHelper.getSystemEncoding());
            multipart.addBodyPart(bodyMessagePart);
        }

        // attach the file to the message
        MimeBodyPart attachmentBodyPart = new MimeBodyPart();
        attachmentBodyPart.setDataHandler(new DataHandler(dataSource));
        attachmentBodyPart.setFileName(MimeUtility.encodeText(attachmentName, "UTF-8", null));
        multipart.addBodyPart(attachmentBodyPart);

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

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

        Transport.send(msg);

        return true;
    } catch (SendFailedException e) {
        logger.error("Email.ERROR_0011_SEND_FAILED -" + to, e); //$NON-NLS-1$
    } catch (AuthenticationFailedException e) {
        logger.error("Email.ERROR_0014_AUTHENTICATION_FAILED - " + to, e); //$NON-NLS-1$
    } catch (Throwable e) {
        logger.error("Email.ERROR_0011_SEND_FAILED - " + to, e); //$NON-NLS-1$
    }
    return false;
}

From source file:it.greenvulcano.gvesb.virtual.utils.MimeMessageHelper.java

public MimeMessage getMimeMessage() throws MessagingException {

    if (attachments.isEmpty()) {
        switch (messageType) {
        case HTML:
            mimeMessage.setContent(messageBody, "text/html; charset=utf-8");
            break;

        case TEXT:
            mimeMessage.setText(messageBody, "UTF-8");
            mimeMessage.addHeader("Content-Transfer-Encoding", "quoted-printable");
            break;
        }// w w  w  . ja va2  s  .  c  o m
    } else {

        MimeBodyPart mimeBodyPart = new MimeBodyPart();

        switch (messageType) {
        case HTML:
            mimeBodyPart.setContent(messageBody, "text/html; charset=utf-8");
            break;

        case TEXT:
            mimeBodyPart.setText(messageBody, "UTF-8");
            mimeMessage.addHeader("Content-Transfer-Encoding", "quoted-printable");
            break;
        }

        mimeBodyPart.setDisposition(Part.INLINE);

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

        for (BodyPart attachmentPart : attachments) {
            multipart.addBodyPart(attachmentPart);
        }

        mimeMessage.setContent(multipart);
    }

    return mimeMessage;
}

From source file:org.apache.jmeter.protocol.smtp.sampler.protocol.SendMailCommand.java

/**
 * Prepares message prior to be sent via execute()-method, i.e. sets
 * properties such as protocol, authentication, etc.
 *
 * @return Message-object to be sent to execute()-method
 * @throws MessagingException/* w  w w.j a va2 s.  c  o  m*/
 *             when problems constructing or sending the mail occur
 * @throws IOException
 *             when the mail content can not be read or truststore problems
 *             are detected
 */
public Message prepareMessage() throws MessagingException, IOException {

    Properties props = new Properties();

    String protocol = getProtocol();

    // set properties using JAF
    props.setProperty("mail." + protocol + ".host", smtpServer);
    props.setProperty("mail." + protocol + ".port", getPort());
    props.setProperty("mail." + protocol + ".auth", Boolean.toString(useAuthentication));

    // set timeout
    props.setProperty("mail." + protocol + ".timeout", getTimeout());
    props.setProperty("mail." + protocol + ".connectiontimeout", getConnectionTimeout());

    if (useStartTLS || useSSL) {
        try {
            String allProtocols = StringUtils
                    .join(SSLContext.getDefault().getSupportedSSLParameters().getProtocols(), " ");
            logger.info("Use ssl/tls protocols for mail: " + allProtocols);
            props.setProperty("mail." + protocol + ".ssl.protocols", allProtocols);
        } catch (Exception e) {
            logger.error("Problem setting ssl/tls protocols for mail", e);
        }
    }

    if (enableDebug) {
        props.setProperty("mail.debug", "true");
    }

    if (useStartTLS) {
        props.setProperty("mail.smtp.starttls.enable", "true");
        if (enforceStartTLS) {
            // Requires JavaMail 1.4.2+
            props.setProperty("mail.smtp.starttls.require", "true");
        }
    }

    if (trustAllCerts) {
        if (useSSL) {
            props.setProperty("mail.smtps.ssl.socketFactory.class", TRUST_ALL_SOCKET_FACTORY);
            props.setProperty("mail.smtps.ssl.socketFactory.fallback", "false");
        } else if (useStartTLS) {
            props.setProperty("mail.smtp.ssl.socketFactory.class", TRUST_ALL_SOCKET_FACTORY);
            props.setProperty("mail.smtp.ssl.socketFactory.fallback", "false");
        }
    } else if (useLocalTrustStore) {
        File truststore = new File(trustStoreToUse);
        logger.info("load local truststore - try to load truststore from: " + truststore.getAbsolutePath());
        if (!truststore.exists()) {
            logger.info(
                    "load local truststore -Failed to load truststore from: " + truststore.getAbsolutePath());
            truststore = new File(FileServer.getFileServer().getBaseDir(), trustStoreToUse);
            logger.info("load local truststore -Attempting to read truststore from:  "
                    + truststore.getAbsolutePath());
            if (!truststore.exists()) {
                logger.info(
                        "load local truststore -Failed to load truststore from: " + truststore.getAbsolutePath()
                                + ". Local truststore not available, aborting execution.");
                throw new IOException("Local truststore file not found. Also not available under : "
                        + truststore.getAbsolutePath());
            }
        }
        if (useSSL) {
            // Requires JavaMail 1.4.2+
            props.put("mail.smtps.ssl.socketFactory", new LocalTrustStoreSSLSocketFactory(truststore));
            props.put("mail.smtps.ssl.socketFactory.fallback", "false");
        } else if (useStartTLS) {
            // Requires JavaMail 1.4.2+
            props.put("mail.smtp.ssl.socketFactory", new LocalTrustStoreSSLSocketFactory(truststore));
            props.put("mail.smtp.ssl.socketFactory.fallback", "false");
        }
    }

    session = Session.getInstance(props, null);

    Message message;

    if (sendEmlMessage) {
        message = new MimeMessage(session, new BufferedInputStream(new FileInputStream(emlMessage)));
    } else {
        message = new MimeMessage(session);
        // handle body and attachments
        Multipart multipart = new MimeMultipart();
        final int attachmentCount = attachments.size();
        if (plainBody && (attachmentCount == 0 || (mailBody.length() == 0 && attachmentCount == 1))) {
            if (attachmentCount == 1) { // i.e. mailBody is empty
                File first = attachments.get(0);
                InputStream is = null;
                try {
                    is = new BufferedInputStream(new FileInputStream(first));
                    message.setText(IOUtils.toString(is));
                } finally {
                    IOUtils.closeQuietly(is);
                }
            } else {
                message.setText(mailBody);
            }
        } else {
            BodyPart body = new MimeBodyPart();
            body.setText(mailBody);
            multipart.addBodyPart(body);
            for (File f : attachments) {
                BodyPart attach = new MimeBodyPart();
                attach.setFileName(f.getName());
                attach.setDataHandler(new DataHandler(new FileDataSource(f.getAbsolutePath())));
                multipart.addBodyPart(attach);
            }
            message.setContent(multipart);
        }
    }

    // set from field and subject
    if (null != sender) {
        message.setFrom(new InternetAddress(sender));
    }

    if (null != replyTo) {
        InternetAddress[] to = new InternetAddress[replyTo.size()];
        message.setReplyTo(replyTo.toArray(to));
    }

    if (null != subject) {
        message.setSubject(subject);
    }

    if (receiverTo != null) {
        InternetAddress[] to = new InternetAddress[receiverTo.size()];
        receiverTo.toArray(to);
        message.setRecipients(Message.RecipientType.TO, to);
    }

    if (receiverCC != null) {
        InternetAddress[] cc = new InternetAddress[receiverCC.size()];
        receiverCC.toArray(cc);
        message.setRecipients(Message.RecipientType.CC, cc);
    }

    if (receiverBCC != null) {
        InternetAddress[] bcc = new InternetAddress[receiverBCC.size()];
        receiverBCC.toArray(bcc);
        message.setRecipients(Message.RecipientType.BCC, bcc);
    }

    for (int i = 0; i < headerFields.size(); i++) {
        Argument argument = (Argument) ((TestElementProperty) headerFields.get(i)).getObjectValue();
        message.setHeader(argument.getName(), argument.getValue());
    }

    message.saveChanges();
    return message;
}

From source file:com.ctriposs.r2.message.rest.QueryTunnelUtil.java

/**
 * Helper function to create multi-part MIME
 *
 * @param entity         the body of a request
 * @param entityContentType content type of the body
 * @param query          a query part of a request
 *
 * @return a ByteString that represents a multi-part encoded entity that contains both
 *///from   ww w.  j a v  a 2 s. c o m
private static MimeMultipart createMultiPartEntity(ByteString entity, String entityContentType, String query)
        throws MessagingException {
    MimeMultipart multi = new MimeMultipart(MIXED);

    // Create current entity with the associated type
    MimeBodyPart dataPart = new MimeBodyPart();

    ContentType contentType = new ContentType(entityContentType);
    dataPart.setContent(entity.copyBytes(), contentType.getBaseType());
    dataPart.setHeader(HEADER_CONTENT_TYPE, entityContentType);

    // Encode query params as form-urlencoded
    MimeBodyPart argPart = new MimeBodyPart();
    argPart.setContent(query, FORM_URL_ENCODED);
    argPart.setHeader(HEADER_CONTENT_TYPE, FORM_URL_ENCODED);

    multi.addBodyPart(argPart);
    multi.addBodyPart(dataPart);
    return multi;
}