Example usage for javax.mail.internet MimeBodyPart setDisposition

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

Introduction

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

Prototype

@Override
public void setDisposition(String disposition) throws MessagingException 

Source Link

Document

Set the disposition in the "Content-Disposition" header field of this body part.

Usage

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

@SuppressWarnings("deprecation")
@Override/*  w ww. ja v a 2  s.  c om*/
public void filterHttpRequest(SubmitContext context, HttpRequestInterface<?> request) {
    HttpRequestBase httpMethod = (HttpRequestBase) context.getProperty(BaseHttpRequestTransport.HTTP_METHOD);

    String path = PropertyExpander.expandProperties(context, request.getPath());
    StringBuffer query = new StringBuffer();
    String encoding = System.getProperty("soapui.request.encoding", StringUtils.unquote(request.getEncoding()));

    StringToStringMap responseProperties = (StringToStringMap) context
            .getProperty(BaseHttpRequestTransport.RESPONSE_PROPERTIES);

    MimeMultipart formMp = "multipart/form-data".equals(request.getMediaType())
            && httpMethod instanceof HttpEntityEnclosingRequestBase ? new MimeMultipart() : null;

    RestParamsPropertyHolder params = request.getParams();

    for (int c = 0; c < params.getPropertyCount(); c++) {
        RestParamProperty param = params.getPropertyAt(c);

        String value = PropertyExpander.expandProperties(context, param.getValue());
        responseProperties.put(param.getName(), value);

        List<String> valueParts = sendEmptyParameters(request)
                || (!StringUtils.hasContent(value) && param.getRequired())
                        ? RestUtils.splitMultipleParametersEmptyIncluded(value,
                                request.getMultiValueDelimiter())
                        : RestUtils.splitMultipleParameters(value, request.getMultiValueDelimiter());

        // skip HEADER and TEMPLATE parameter encoding (TEMPLATE is encoded by
        // the URI handling further down)
        if (value != null && param.getStyle() != ParameterStyle.HEADER
                && param.getStyle() != ParameterStyle.TEMPLATE && !param.isDisableUrlEncoding()) {
            try {
                if (StringUtils.hasContent(encoding)) {
                    value = URLEncoder.encode(value, encoding);
                    for (int i = 0; i < valueParts.size(); i++)
                        valueParts.set(i, URLEncoder.encode(valueParts.get(i), encoding));
                } else {
                    value = URLEncoder.encode(value);
                    for (int i = 0; i < valueParts.size(); i++)
                        valueParts.set(i, URLEncoder.encode(valueParts.get(i)));
                }
            } catch (UnsupportedEncodingException e1) {
                SoapUI.logError(e1);
                value = URLEncoder.encode(value);
                for (int i = 0; i < valueParts.size(); i++)
                    valueParts.set(i, URLEncoder.encode(valueParts.get(i)));
            }
            // URLEncoder replaces space with "+", but we want "%20".
            value = value.replaceAll("\\+", "%20");
            for (int i = 0; i < valueParts.size(); i++)
                valueParts.set(i, valueParts.get(i).replaceAll("\\+", "%20"));
        }

        if (param.getStyle() == ParameterStyle.QUERY && !sendEmptyParameters(request)) {
            if (!StringUtils.hasContent(value) && !param.getRequired())
                continue;
        }

        switch (param.getStyle()) {
        case HEADER:
            for (String valuePart : valueParts)
                httpMethod.addHeader(param.getName(), valuePart);
            break;
        case QUERY:
            if (formMp == null || !request.isPostQueryString()) {
                for (String valuePart : valueParts) {
                    if (query.length() > 0)
                        query.append('&');

                    query.append(URLEncoder.encode(param.getName()));
                    query.append('=');
                    if (StringUtils.hasContent(valuePart))
                        query.append(valuePart);
                }
            } else {
                try {
                    addFormMultipart(request, formMp, param.getName(), responseProperties.get(param.getName()));
                } catch (MessagingException e) {
                    SoapUI.logError(e);
                }
            }

            break;
        case TEMPLATE:
            try {
                value = getEncodedValue(value, encoding, param.isDisableUrlEncoding(),
                        request.getSettings().getBoolean(HttpSettings.ENCODED_URLS));
                path = path.replaceAll("\\{" + param.getName() + "\\}", value == null ? "" : value);
            } catch (UnsupportedEncodingException e) {
                SoapUI.logError(e);
            }
            break;
        case MATRIX:
            try {
                value = getEncodedValue(value, encoding, param.isDisableUrlEncoding(),
                        request.getSettings().getBoolean(HttpSettings.ENCODED_URLS));
            } catch (UnsupportedEncodingException e) {
                SoapUI.logError(e);
            }

            if (param.getType().equals(XmlBoolean.type.getName())) {
                if (value.toUpperCase().equals("TRUE") || value.equals("1")) {
                    path += ";" + param.getName();
                }
            } else {
                path += ";" + param.getName();
                if (StringUtils.hasContent(value)) {
                    path += "=" + value;
                }
            }
        case PLAIN:
            break;
        }
    }

    if (request.getSettings().getBoolean(HttpSettings.FORWARD_SLASHES))
        path = PathUtils.fixForwardSlashesInPath(path);

    if (PathUtils.isHttpPath(path)) {
        try {
            // URI(String) automatically URLencodes the input, so we need to
            // decode it first...
            URI uri = new URI(path, request.getSettings().getBoolean(HttpSettings.ENCODED_URLS));
            context.setProperty(BaseHttpRequestTransport.REQUEST_URI, uri);
            java.net.URI oldUri = httpMethod.getURI();
            httpMethod.setURI(new java.net.URI(oldUri.getScheme(), oldUri.getUserInfo(), oldUri.getHost(),
                    oldUri.getPort(), (uri.getPath()) == null ? "/" : uri.getPath(), oldUri.getQuery(),
                    oldUri.getFragment()));
        } catch (Exception e) {
            SoapUI.logError(e);
        }
    } else if (StringUtils.hasContent(path)) {
        try {
            java.net.URI oldUri = httpMethod.getURI();
            String pathToSet = StringUtils.hasContent(oldUri.getRawPath()) && !"/".equals(oldUri.getRawPath())
                    ? oldUri.getRawPath() + path
                    : path;
            java.net.URI newUri = URIUtils.createURI(oldUri.getScheme(), oldUri.getHost(), oldUri.getPort(),
                    pathToSet, oldUri.getQuery(), oldUri.getFragment());
            httpMethod.setURI(newUri);
            context.setProperty(BaseHttpRequestTransport.REQUEST_URI,
                    new URI(newUri.toString(), request.getSettings().getBoolean(HttpSettings.ENCODED_URLS)));
        } catch (Exception e) {
            SoapUI.logError(e);
        }
    }

    if (query.length() > 0 && !request.isPostQueryString()) {
        try {
            java.net.URI oldUri = httpMethod.getURI();
            httpMethod.setURI(URIUtils.createURI(oldUri.getScheme(), oldUri.getHost(), oldUri.getPort(),
                    oldUri.getRawPath(), query.toString(), oldUri.getFragment()));
        } catch (Exception e) {
            SoapUI.logError(e);
        }
    }

    if (request instanceof RestRequest) {
        String acceptEncoding = ((RestRequest) request).getAccept();
        if (StringUtils.hasContent(acceptEncoding)) {
            httpMethod.setHeader("Accept", acceptEncoding);
        }
    }

    if (formMp != null) {
        // create request message
        try {
            if (request.hasRequestBody() && httpMethod instanceof HttpEntityEnclosingRequest) {
                String requestContent = PropertyExpander.expandProperties(context, request.getRequestContent(),
                        request.isEntitizeProperties());
                if (StringUtils.hasContent(requestContent)) {
                    initRootPart(request, requestContent, formMp);
                }
            }

            for (Attachment attachment : request.getAttachments()) {
                MimeBodyPart part = new PreencodedMimeBodyPart("binary");

                if (attachment instanceof FileAttachment<?>) {
                    String name = attachment.getName();
                    if (StringUtils.hasContent(attachment.getContentID())
                            && !name.equals(attachment.getContentID()))
                        name = attachment.getContentID();

                    part.setDisposition(
                            "form-data; name=\"" + name + "\"; filename=\"" + attachment.getName() + "\"");
                } else
                    part.setDisposition("form-data; name=\"" + attachment.getName() + "\"");

                part.setDataHandler(new DataHandler(new AttachmentDataSource(attachment)));

                formMp.addBodyPart(part);
            }

            MimeMessage message = new MimeMessage(AttachmentUtils.JAVAMAIL_SESSION);
            message.setContent(formMp);
            message.saveChanges();
            RestRequestMimeMessageRequestEntity mimeMessageRequestEntity = new RestRequestMimeMessageRequestEntity(
                    message, request);
            ((HttpEntityEnclosingRequest) httpMethod).setEntity(mimeMessageRequestEntity);
            httpMethod.setHeader("Content-Type", mimeMessageRequestEntity.getContentType().getValue());
            httpMethod.setHeader("MIME-Version", "1.0");
        } catch (Throwable e) {
            SoapUI.logError(e);
        }
    } else if (request.hasRequestBody() && httpMethod instanceof HttpEntityEnclosingRequest) {
        if (StringUtils.hasContent(request.getMediaType()))
            httpMethod.setHeader("Content-Type", getContentTypeHeader(request.getMediaType(), encoding));

        if (request.isPostQueryString()) {
            try {
                ((HttpEntityEnclosingRequest) httpMethod).setEntity(new StringEntity(query.toString()));
            } catch (UnsupportedEncodingException e) {
                SoapUI.logError(e);
            }
        } else {
            String requestContent = PropertyExpander.expandProperties(context, request.getRequestContent(),
                    request.isEntitizeProperties());
            List<Attachment> attachments = new ArrayList<Attachment>();

            for (Attachment attachment : request.getAttachments()) {
                if (attachment.getContentType().equals(request.getMediaType())) {
                    attachments.add(attachment);
                }
            }

            if (StringUtils.hasContent(requestContent) && attachments.isEmpty()) {
                try {
                    byte[] content = encoding == null ? requestContent.getBytes()
                            : requestContent.getBytes(encoding);
                    ((HttpEntityEnclosingRequest) httpMethod).setEntity(new ByteArrayEntity(content));
                } catch (UnsupportedEncodingException e) {
                    ((HttpEntityEnclosingRequest) httpMethod)
                            .setEntity(new ByteArrayEntity(requestContent.getBytes()));
                }
            } else if (attachments.size() > 0) {
                try {
                    MimeMultipart mp = null;

                    if (StringUtils.hasContent(requestContent)) {
                        mp = new MimeMultipart();
                        initRootPart(request, requestContent, mp);
                    } else if (attachments.size() == 1) {
                        ((HttpEntityEnclosingRequest) httpMethod)
                                .setEntity(new InputStreamEntity(attachments.get(0).getInputStream(), -1));

                        httpMethod.setHeader("Content-Type",
                                getContentTypeHeader(request.getMediaType(), encoding));
                    }

                    if (((HttpEntityEnclosingRequest) httpMethod).getEntity() == null) {
                        if (mp == null)
                            mp = new MimeMultipart();

                        // init mimeparts
                        AttachmentUtils.addMimeParts(request, attachments, mp, new StringToStringMap());

                        // create request message
                        MimeMessage message = new MimeMessage(AttachmentUtils.JAVAMAIL_SESSION);
                        message.setContent(mp);
                        message.saveChanges();
                        RestRequestMimeMessageRequestEntity mimeMessageRequestEntity = new RestRequestMimeMessageRequestEntity(
                                message, request);
                        ((HttpEntityEnclosingRequest) httpMethod).setEntity(mimeMessageRequestEntity);
                        httpMethod.setHeader("Content-Type", getContentTypeHeader(
                                mimeMessageRequestEntity.getContentType().getValue(), encoding));
                        httpMethod.setHeader("MIME-Version", "1.0");
                    }
                } catch (Exception e) {
                    SoapUI.logError(e);
                }
            }
        }
    }
}

From source file:com.xpn.xwiki.plugin.mailsender.MailSenderPlugin.java

/**
 * Add attachments to a multipart message
 * //from ww w.  j av a2  s .c  o  m
 * @param multipart Multipart message
 * @param attachments List of attachments
 */
public MimeBodyPart createAttachmentBodyPart(Attachment attachment, XWikiContext context)
        throws XWikiException, IOException, MessagingException {
    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;
}

From source file:com.eviware.soapui.impl.wsdl.submit.transports.http.support.attachments.AttachmentUtils.java

public static void initPartContentId(StringToStringMap contentIds, MimeBodyPart part, Attachment attachment,
        boolean isMultipart) throws MessagingException {
    String partName = attachment.getPart();

    String contentID = attachment.getContentID();
    if (StringUtils.hasContent(contentID)) {
        contentID = contentID.trim();/*from  ww  w  . j a  v a2s .c o m*/
        int ix = contentID.indexOf(' ');
        if (ix != -1)
            part.setContentID(
                    "<" + (isMultipart ? contentID.substring(ix + 1) : contentID.substring(0, ix)) + ">");
        else {
            if (!contentID.startsWith("<"))
                contentID = "<" + contentID;

            if (!contentID.endsWith(">"))
                contentID = contentID + ">";

            part.setContentID(contentID);
        }
    } else if (partName != null && !partName.equals(HttpAttachmentPart.ANONYMOUS_NAME)) {
        if (contentIds.containsKey(partName)) {
            part.setContentID("<" + contentIds.get(partName) + ">");
        } else {
            part.setContentID("<" + partName + "=" + System.nanoTime() + "@soapui.org>");
        }
    }

    // set content-disposition
    String name = attachment.getName();
    String file = attachment.getUrl();
    if (PathUtils.isFilePath(file)) {
        int ix = file.lastIndexOf(File.separatorChar);
        if (ix == -1)
            ix = file.lastIndexOf('/');

        if (ix > 0 && ix < file.length() - 1)
            file = file.substring(ix + 1);

        part.setDisposition("attachment; name=\"" + name + "\"; filename=\"" + file + "\"");
    } else {
        part.setDisposition("attachment; name=\"" + name + "\"");
    }
}

From source file:au.aurin.org.controller.RestController.java

public Boolean sendEmail(final String randomUUIDString, final String password, final String email,
        final List<String> lstApps, final String fullName) throws IOException {
    final String clink = classmail.getUrl() + "authchangepassword/" + randomUUIDString;

    logger.info("Starting sending Email to:" + email);
    String msg = "";

    if (!fullName.equals("")) {
        msg = msg + "Dear " + fullName + "<br>";
    }/*from w w w.j a  va2s . com*/
    Boolean lswWhatIf = false;
    if (lstApps != null) {
        //msg = msg + "You have been given access to the following applications: <br>";
        msg = msg + "<br>You have been given access to the following applications: <br>";
        for (final String st : lstApps) {
            if (st.toLowerCase().contains("whatif") || st.toLowerCase().contains("what if")) {

                lswWhatIf = true;
            }
            msg = "<br>" + msg + st + "<br>";
        }

    }

    msg = msg + "<br>Your current password is : " + password
            + " <br> To customise the password please change it using link below: <br> <a href='" + clink
            + "'> change password </a><br><br>After changing your password you can log in to the applications using your email and password. ";

    final String subject = "AURIN Workbench Access";

    final String from = classmail.getFrom();
    final String to = email;

    if (lswWhatIf == true) {
        msg = msg
                + "<br><br>If you require further support to establish a project within Online WhatIf please email your request to support@aurin.org.au";
        msg = msg + "<br>For other related requests please contact one of the members of the project team.";
        msg = msg + "<br><br>Kind Regards,";
        msg = msg + "<br>The Online WhatIf team<br>";
        msg = msg
                + "<br><strong>Prof Christopher Pettit</strong>&nbsp;&nbsp;&nbsp;&nbsp;Online WhatIf Project Director, City Futures (c.pettit@unsw.edu.au)";
        msg = msg
                + "<br><strong>Claudia Pelizaro</strong>&nbsp;&nbsp;&nbsp;&nbsp;Online WhatIf Project Manager, AURIN (claudia.pelizaro@unimelb.edu.au)";
        msg = msg
                + "<br><strong>Andrew Dingjan</strong>&nbsp;&nbsp;&nbsp;&nbsp;Director, AURIN (andrew.dingjan@unimelb.edu.au)";
        msg = msg
                + "<br><strong>Serryn Eagleson</strong>&nbsp;&nbsp;&nbsp;&nbsp;Manager Data and Business Analytics (serrynle@unimelb.edu.au)";

    } else {
        msg = msg + "<br><br>Kind Regards,";
        msg = msg + "<br>The AURIN Workbench team";
    }

    try {
        final Message message = new MimeMessage(getSession());

        message.addRecipient(RecipientType.TO, new InternetAddress(to));
        message.addFrom(new InternetAddress[] { new InternetAddress(from) });

        message.setSubject(subject);
        message.setContent(msg, "text/html");

        //////////////////////////////////
        final MimeMultipart multipart = new MimeMultipart("related");
        final BodyPart messageBodyPart = new MimeBodyPart();
        //final String htmlText = "<H1>Hello</H1><img src=\"cid:image\">";

        msg = msg + "<br><br><img src=\"cid:AbcXyz123\" />";
        //msg = msg + "<img src=\"cid:image\">";
        messageBodyPart.setContent(msg, "text/html");
        // add it
        multipart.addBodyPart(messageBodyPart);

        /////// second part (the image)
        //      messageBodyPart = new MimeBodyPart();
        final URL peopleresource = getClass().getResource("/logo.jpg");
        logger.info(peopleresource.getPath());
        //            final DataSource fds = new FileDataSource(
        //                peopleresource.getPath());
        //
        //      messageBodyPart.setDataHandler(new DataHandler(fds));
        //      messageBodyPart.setHeader("Content-ID", "<image>");
        //      // add image to the multipart
        //      //multipart.addBodyPart(messageBodyPart);

        ///////////
        final MimeBodyPart imagePart = new MimeBodyPart();
        imagePart.attachFile(peopleresource.getPath());
        //      final String cid = "1";
        //      imagePart.setContentID("<" + cid + ">");
        imagePart.setHeader("Content-ID", "AbcXyz123");
        imagePart.setDisposition(MimeBodyPart.INLINE);
        multipart.addBodyPart(imagePart);

        // put everything together
        message.setContent(multipart);
        ////////////////////////////////

        Transport.send(message);
        logger.info("Email sent to:" + email);
    } catch (final Exception mex) {
        logger.info(mex.toString());
        return false;
    }

    return true;
}

From source file:com.duroty.utils.mail.MessageUtilities.java

/**
 * DOCUMENT ME!/*w  ww  .  j  a  v a 2 s  .com*/
 *
 * @param multipart DOCUMENT ME!
 * @param file DOCUMENT ME!
 * @param charset DOCUMENT ME!
 *
 * @throws MessagingException DOCUMENT ME!
 */
public static void attach(MimeMultipart multipart, File file, String charset) throws MessagingException {
    // UNDONE how to specify the character set of the file???
    MimeBodyPart xbody = new MimeBodyPart();
    FileDataSource xds = new FileDataSource(file);
    DataHandler xdh = new DataHandler(xds);
    xbody.setDataHandler(xdh);

    //System.out.println(xdh.getContentType());
    // UNDONE
    // xbody.setContentLanguage( String ); // this could be language from Locale
    // xbody.setContentMD5( String md5 ); // don't know about this yet
    xbody.setDescription("File Attachment: " + file.getName(), charset);
    xbody.setDisposition(Part.ATTACHMENT);
    MessageUtilities.setFileName(xbody, file.getName(), charset);

    multipart.addBodyPart(xbody);
}

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//www . j av  a  2 s  . c  om
        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.duroty.utils.mail.MessageUtilities.java

/**
 * DOCUMENT ME!//from   ww w . j ava2  s  . com
 *
 * @param multipart DOCUMENT ME!
 * @param text DOCUMENT ME!
 * @param charset DOCUMENT ME!
 * @param disposition DOCUMENT ME!
 *
 * @throws MessagingException DOCUMENT ME!
 */
public static void attach(MimeMultipart multipart, String text, String charset, String disposition,
        boolean isHtml) throws MessagingException {
    int xid = multipart.getCount() + 1;

    MimeBodyPart xbody = new MimeBodyPart();

    String xname = null;

    if (isHtml) {
        xname = "HTML" + xid + ".html";
        xbody.setContent(text, "text/html" + "; charset=" + charset);
        xbody.setDescription("Html Attachment: " + xname, charset);
    } else {
        xname = "TEXT" + xid + ".txt";
        xbody.setText(text, charset);
        xbody.setDescription("Text Attachment: " + xname, charset);
    }

    // UNDONE
    //xbody.setContentLanguage( String ); // this could be language from Locale
    //xbody.setContentMD5( String md5 ); // don't know about this yet        
    xbody.setDisposition(disposition);
    MessageUtilities.setFileName(xbody, xname, charset);

    multipart.addBodyPart(xbody);
}

From source file:com.duroty.utils.mail.MessageUtilities.java

/**
 * DOCUMENT ME!/* w ww .  ja  va  2  s  .c  o m*/
 *
 * @param multipart DOCUMENT ME!
 * @param part DOCUMENT ME!
 * @param charset DOCUMENT ME!
 *
 * @throws MessagingException DOCUMENT ME!
 */
public static void attach(MimeMultipart multipart, Part part, String charset) throws MessagingException {
    MimeBodyPart xbody = new MimeBodyPart();
    PartDataSource xds = new PartDataSource(part);
    DataHandler xdh = new DataHandler(xds);
    xbody.setDataHandler(xdh);

    int xid = multipart.getCount() + 1;
    String xtext;

    // UNDONE
    //xbody.setContentLanguage( String ); // this could be language from Locale
    //xbody.setContentMD5( String md5 ); // don't know about this yet
    xtext = part.getDescription();

    if (xtext == null) {
        xtext = "Part Attachment: " + xid;
    }

    xbody.setDescription(xtext, charset);

    xtext = getContentDisposition(part).getType();
    xbody.setDisposition(xtext);

    xtext = MessageUtilities.getFileName(part);

    if ((xtext == null) || (xtext.length() < 1)) {
        xtext = "PART" + xid;
    }

    MessageUtilities.setFileName(xbody, xtext, charset);

    multipart.addBodyPart(xbody);
}

From source file:Implement.Service.ProviderServiceImpl.java

@Override
public boolean sendEmailReferral(String data, int providerID, String baseUrl) throws MessagingException {
    final String username = "registration@youtripper.com";
    final String password = "Tripregister190515";

    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);
        }/*www .  ja  va2s.c o m*/
    });

    String title = "You have an invitation from your friend.";

    JsonObject jsonObject = gson.fromJson(data, JsonObject.class);
    String content = jsonObject.get("content").getAsString();
    JsonArray sportsArray = jsonObject.get("emails").getAsJsonArray();
    ArrayList<String> listEmail = new ArrayList<>();
    if (sportsArray != null) {
        for (int i = 0; i < sportsArray.size(); i++) {
            listEmail.add(sportsArray.get(i).getAsString());
        }
    }

    String path = System.getProperty("catalina.base");
    MimeBodyPart backgroundImage = new MimeBodyPart();
    // attach the file to the message
    DataSource source = new FileDataSource(new File(path + "/webapps/Images/Email/backgroundImage.png"));
    backgroundImage.setDataHandler(new DataHandler(source));
    backgroundImage.setFileName("backgroundImage.png");
    backgroundImage.setDisposition(MimeBodyPart.INLINE);
    backgroundImage.setHeader("Content-ID", "<bg_Icon>"); // cid:image_cid

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

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

    Multipart mp = new MimeMultipart("related");
    mp.addBodyPart(mbp1);
    Message message = new MimeMessage(session);
    message.setFrom(new InternetAddress("registration@youtripper.com"));
    String addresses = "";
    for (int i = 0; i < listEmail.size(); i++) {
        if (i < listEmail.size() - 1) {
            addresses = addresses + listEmail.get(i) + ",";
        } else {
            addresses = addresses + listEmail.get(i);
        }
    }

    message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(addresses));

    message.setSubject(title);
    message.setContent(mp);
    message.saveChanges();
    try {
        Transport.send(message);
    } catch (Exception e) {
        e.printStackTrace();
    }

    System.out.println("sent");
    return true;
}

From source file:Implement.Service.ProviderServiceImpl.java

@Override
public boolean sendMail(HttpServletRequest request, String providerName, int providerID, String baseUrl)
        throws MessagingException {
    final String username = "registration@youtripper.com";
    final String password = "Tripregister190515";

    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", "smtpm.csloxinfo.com");

    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }/* w  w w .j  av  a2  s .c o  m*/
    });

    //Create data for referral
    java.util.Date date = new java.util.Date();
    String s = providerID + (new Timestamp(date.getTime()).toString());
    MessageDigest m = null;
    try {
        m = MessageDigest.getInstance("MD5");

    } catch (NoSuchAlgorithmException ex) {
        Logger.getLogger(ProviderServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
    }
    m.update(s.getBytes(), 0, s.length());
    String md5 = (new BigInteger(1, m.digest()).toString(16));

    String title = "You have an invitation from your friend.";
    String receiver = request.getParameter("email");

    //        StringBuilder messageContentHtml = new StringBuilder();
    //        messageContentHtml.append(request.getParameter("message") + "<br />\n");
    //        messageContentHtml.append("You can become a provider from here:  " + baseUrl + "/Common/Provider/SignupReferral/" + md5);
    //        String messageContent = messageContentHtml.toString();
    String emailContent = "  <div style='background: url(cid:bg_Icon) no-repeat;background-color:#ebebec;text-align: center;width:610px;height:365px'>"
            + "            <p style='font-size:16px;padding-top: 45px; padding-bottom: 15px;'>Your friend <b>"
            + providerName + "</b> has invited you to complete purchase via</p>"
            + "            <a href='http://youtripper.com/Common/Provider/SignupReferral/" + md5
            + "' style='width: 160px;height: 50px;border-radius: 5px;border: 0;"
            + "                    background-color: #ff514e;font-size: 14px;font-weight: bolder;color: #fff;display: block;line-height: 50px;margin: 0 auto;text-decoration:none;' >Refferal Link</a>"
            + "            <p style='font-size:16px;margin:30px;'><b>" + providerName
            + "</b> will get 25 credit</p>"
            + "            <a href='http://youtripper.com' target='_blank'><img src='cid:gift_Icon' width='90' height='90'></a>"
            + "            <a href='http://youtripper.com' target='_blank' style='font-size:10px;color:#939598;text-decoration:none'><p>from www.youtripper.com</p></a>"
            + "            " + "            " + "        </div>";

    String path = System.getProperty("catalina.base");
    MimeBodyPart backgroundImage = new MimeBodyPart();
    // attach the file to the message
    DataSource source = new FileDataSource(new File(path + "/webapps/Images/Email/backgroundImage.png"));
    backgroundImage.setDataHandler(new DataHandler(source));
    backgroundImage.setFileName("backgroundImage.png");
    backgroundImage.setDisposition(MimeBodyPart.INLINE);
    backgroundImage.setHeader("Content-ID", "<bg_Icon>"); // cid:image_cid

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

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

    Multipart mp = new MimeMultipart("related");
    mp.addBodyPart(mbp1);
    mp.addBodyPart(backgroundImage);
    mp.addBodyPart(giftImage);
    Message message = new MimeMessage(session);
    message.setFrom(new InternetAddress("registration@youtripper.com"));
    message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(receiver));
    message.setSubject(title);
    message.setContent(mp);
    message.saveChanges();
    Transport.send(message);

    ReferralDTO referral = new ReferralDTO(providerID, receiver, String.valueOf(System.currentTimeMillis()),
            md5, 0);
    referralDAO.insertNewReferral(referral);
    return true;
}