Example usage for javax.mail.internet MimeMultipart MimeMultipart

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

Introduction

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

Prototype

public MimeMultipart(DataSource ds) throws MessagingException 

Source Link

Document

Constructs a MimeMultipart object and its bodyparts from the given DataSource.

Usage

From source file:it.greenvulcano.gvesb.virtual.http.HTTPCallOperation.java

/**
 * @param responseBody/* ww w  .  ja  va 2s  .  c  om*/
 * @throws MessagingException
 */
private Document handleMultipart(byte[] responseBody, String contentType) throws Exception {
    ByteArrayDataSource bads = new ByteArrayDataSource(responseBody, contentType);
    MimeMultipart multipart = new MimeMultipart(bads);
    XMLUtils xml = XMLUtils.getParserInstance();
    Document doc = null;
    try {
        doc = xml.newDocument("MultipartHttpResponse");
    } finally {
        XMLUtils.releaseParserInstance(xml);
    }
    for (int i = 0; i < multipart.getCount(); i++) {
        dumpPart(multipart.getBodyPart(i), doc.getDocumentElement(), doc);
    }
    return doc;
}

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

/**
 * Send a Multipart HTML message with the attachements associated to the
 * message and attached files. FIXME: use prepareMessage method
 *
 * @param strRecipientsTo// w  ww .  ja v a  2 s . c o  m
 *            The list of the main recipients email.Every recipient must be
 *            separated by the mail separator defined in config.properties
 * @param strRecipientsCc
 *            The recipients list of the carbon copies .
 * @param strRecipientsBcc
 *            The recipients list of the blind carbon copies .
 * @param strSenderName
 *            The sender name.
 * @param strSenderEmail
 *            The sender email address.
 * @param strSubject
 *            The message subject.
 * @param strMessage
 *            The message.
 * @param urlAttachements
 *            The List of UrlAttachement Object, containing the URL of
 *            attachments associated with their content-location.
 * @param fileAttachements
 *            The list of files attached
 * @param transport
 *            the smtp transport object
 * @param session
 *            the smtp session object
 * @throws AddressException
 *             If invalid address
 * @throws SendFailedException
 *             If an error occured during sending
 * @throws MessagingException
 *             If a messaging error occurred
 */
protected static void sendMultipartMessageHtml(String strRecipientsTo, String strRecipientsCc,
        String strRecipientsBcc, String strSenderName, String strSenderEmail, String strSubject,
        String strMessage, List<UrlAttachment> urlAttachements, List<FileAttachment> fileAttachements,
        Transport transport, Session session) throws MessagingException, AddressException, SendFailedException {
    Message msg = prepareMessage(strRecipientsTo, strRecipientsCc, strRecipientsBcc, strSenderName,
            strSenderEmail, strSubject, session);
    msg.setHeader(HEADER_NAME, HEADER_VALUE);

    // Creation of the root part containing all the elements of the message
    MimeMultipart multipart = ((fileAttachements == null) || (fileAttachements.isEmpty()))
            ? new MimeMultipart(MULTIPART_RELATED)
            : new MimeMultipart();

    // Creation of the html part, the "core" of the message
    BodyPart msgBodyPart = new MimeBodyPart();
    // msgBodyPart.setContent( strMessage, BODY_PART_MIME_TYPE );
    msgBodyPart.setDataHandler(new DataHandler(
            new ByteArrayDataSource(strMessage, AppPropertiesService.getProperty(PROPERTY_MAIL_TYPE_HTML)
                    + AppPropertiesService.getProperty(PROPERTY_CHARSET))));
    multipart.addBodyPart(msgBodyPart);

    if (urlAttachements != null) {
        ByteArrayDataSource urlByteArrayDataSource;

        for (UrlAttachment urlAttachement : urlAttachements) {
            urlByteArrayDataSource = convertUrlAttachmentDataSourceToByteArrayDataSource(urlAttachement);

            if (urlByteArrayDataSource != null) {
                msgBodyPart = new MimeBodyPart();
                // Fill this part, then add it to the root part with the
                // good headers
                msgBodyPart.setDataHandler(new DataHandler(urlByteArrayDataSource));
                msgBodyPart.setHeader(HEADER_CONTENT_LOCATION, urlAttachement.getContentLocation());
                multipart.addBodyPart(msgBodyPart);
            }
        }
    }

    // add File Attachement
    if (fileAttachements != null) {
        for (FileAttachment fileAttachement : fileAttachements) {
            String strFileName = fileAttachement.getFileName();
            byte[] bContentFile = fileAttachement.getData();
            String strContentType = fileAttachement.getType();
            ByteArrayDataSource dataSource = new ByteArrayDataSource(bContentFile, strContentType);
            msgBodyPart = new MimeBodyPart();
            msgBodyPart.setDataHandler(new DataHandler(dataSource));
            msgBodyPart.setFileName(strFileName);
            msgBodyPart.setDisposition(CONSTANT_DISPOSITION_ATTACHMENT);
            multipart.addBodyPart(msgBodyPart);
        }
    }

    msg.setContent(multipart);

    sendMessage(msg, transport);
}

From source file:org.orbeon.oxf.processor.EmailProcessor.java

private void handleBody(PipelineContext pipelineContext, String dataInputSystemId, Part parentPart,
        Element bodyElement) throws Exception {

    // Find out if there are embedded parts
    final Iterator parts = bodyElement.elementIterator("part");
    String multipart;//from   w  w  w .j av a 2  s  .  com
    if (bodyElement.getName().equals("body")) {
        multipart = bodyElement.attributeValue("mime-multipart");
        if (multipart != null && !parts.hasNext())
            throw new OXFException("mime-multipart attribute on body element requires part children elements");
        // TODO: Check following lines, which were doing nothing!
        //            final String contentTypeFromAttribute = NetUtils.getContentTypeMediaType(bodyElement.attributeValue("content-type"));
        //            if (contentTypeFromAttribute != null && contentTypeFromAttribute.startsWith("multipart/"))
        //                contentTypeFromAttribute.substring("multipart/".length());
        if (parts.hasNext() && multipart == null)
            multipart = DEFAULT_MULTIPART;
    } else {
        final String contentTypeAttribute = NetUtils
                .getContentTypeMediaType(bodyElement.attributeValue("content-type"));
        multipart = (contentTypeAttribute != null && contentTypeAttribute.startsWith("multipart/"))
                ? contentTypeAttribute.substring("multipart/".length())
                : null;
    }

    if (multipart != null) {
        // Multipart content is requested
        final MimeMultipart mimeMultipart = new MimeMultipart(multipart);

        // Iterate through parts
        while (parts.hasNext()) {
            final Element partElement = (Element) parts.next();

            final MimeBodyPart mimeBodyPart = new MimeBodyPart();
            handleBody(pipelineContext, dataInputSystemId, mimeBodyPart, partElement);
            mimeMultipart.addBodyPart(mimeBodyPart);
        }

        // Set content on parent part
        parentPart.setContent(mimeMultipart);
    } else {
        // No multipart, just use the content of the element and add to the current part (which can be the main message)
        handlePart(pipelineContext, dataInputSystemId, parentPart, bodyElement);
    }
}

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

private Multipart generateMimeMultipart(Mail mail) throws MessagingException {
    Multipart contentsMultipart = new MimeMultipart("alternative");
    List<String> foundEmbeddedImages = new ArrayList<String>();
    boolean hasAttachment = false;

    if (mail.getContents().size() == 1) // To add an alternative plain part
    {/*from   www.  j a va 2  s.c o m*/
        String[] content = mail.getContents().get(0);
        if (content[0].equals("text/plain")) {
            BodyPart alternativePart = new MimeBodyPart();
            alternativePart.setContent(content[1], content[0] + "; charset=" + EMAIL_ENCODING);
            alternativePart.setHeader("Content-Disposition", "inline");
            alternativePart.setHeader("Content-Transfer-Encoding", "quoted-printable");
            contentsMultipart.addBodyPart(alternativePart);
        }
        if (content[0].equals("text/html")) {
            BodyPart alternativePart = new MimeBodyPart();
            String parsedText = createPlain(content[1]);
            alternativePart.setContent(parsedText, "text/plain; charset=" + EMAIL_ENCODING);
            alternativePart.setHeader("Content-Disposition", "inline");
            alternativePart.setHeader("Content-Transfer-Encoding", "quoted-printable");
            contentsMultipart.addBodyPart(alternativePart);
        }
    }

    for (String[] content : mail.getContents()) {
        BodyPart contentPart = new MimeBodyPart();
        contentPart.setContent(content[1], content[0] + "; charset=" + EMAIL_ENCODING);
        contentPart.setHeader("Content-Disposition", "inline");
        contentPart.setHeader("Content-Transfer-Encoding", "quoted-printable");
        if (content[0].equals("text/html")) {
            boolean hasEmbeddedImages = false;
            List<MimeBodyPart> embeddedImages = new ArrayList<MimeBodyPart>();
            Pattern cidPattern = Pattern.compile("src=('|\")cid:([^'\"]*)('|\")",
                    Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
            Matcher matcher = cidPattern.matcher(content[1]);
            String filename;
            while (matcher.find()) {
                filename = matcher.group(2);
                for (Attachment attachment : mail.getAttachments()) {
                    if (filename.equals(attachment.getFilename())) {
                        hasEmbeddedImages = true;
                        MimeBodyPart part = createAttachmentPart(attachment);
                        embeddedImages.add(part);
                        foundEmbeddedImages.add(filename);
                    }
                }
            }
            if (hasEmbeddedImages) {
                Multipart htmlMultipart = new MimeMultipart("related");
                htmlMultipart.addBodyPart(contentPart);
                for (MimeBodyPart imagePart : embeddedImages) {
                    htmlMultipart.addBodyPart(imagePart);
                }
                BodyPart HtmlWrapper = new MimeBodyPart();
                HtmlWrapper.setContent(htmlMultipart);
                contentsMultipart.addBodyPart(HtmlWrapper);
            } else
                contentsMultipart.addBodyPart(contentPart);
        } else {
            contentsMultipart.addBodyPart(contentPart);
        }
    }

    Multipart attachmentsMultipart = new MimeMultipart();
    for (Attachment attachment : mail.getAttachments()) {
        if (!foundEmbeddedImages.contains(attachment.getFilename())) {
            hasAttachment = true;
            MimeBodyPart part = this.createAttachmentPart(attachment);
            attachmentsMultipart.addBodyPart(part);
        }
    }
    if (hasAttachment) {
        Multipart wrapper = new MimeMultipart("mixed");
        BodyPart body = new MimeBodyPart();
        body.setContent(contentsMultipart);
        wrapper.addBodyPart(body);
        BodyPart attachments = new MimeBodyPart();
        attachments.setContent(attachmentsMultipart);
        wrapper.addBodyPart(attachments);
        return wrapper;
    }
    return contentsMultipart;
}

From source file:voldemort.restclient.R2Store.java

private List<Versioned<byte[]>> parseGetResponse(ByteString entity) {
    List<Versioned<byte[]>> results = new ArrayList<Versioned<byte[]>>();

    try {/*from  ww  w . jav a  2  s  .  c  o m*/
        // Build the multipart object
        byte[] bytes = new byte[entity.length()];
        entity.copyBytes(bytes, 0);

        ByteArrayDataSource ds = new ByteArrayDataSource(bytes, "multipart/mixed");
        MimeMultipart mp = new MimeMultipart(ds);
        for (int i = 0; i < mp.getCount(); i++) {
            MimeBodyPart part = (MimeBodyPart) mp.getBodyPart(i);
            String serializedVC = part.getHeader(RestMessageHeaders.X_VOLD_VECTOR_CLOCK)[0];
            int contentLength = Integer.parseInt(part.getHeader(RestMessageHeaders.CONTENT_LENGTH)[0]);

            if (logger.isDebugEnabled()) {
                logger.debug("Received VC : " + serializedVC);
            }
            VectorClockWrapper vcWrapper = mapper.readValue(serializedVC, VectorClockWrapper.class);

            InputStream input = part.getInputStream();
            byte[] bodyPartBytes = new byte[contentLength];
            input.read(bodyPartBytes);

            VectorClock clock = new VectorClock(vcWrapper.getVersions(), vcWrapper.getTimestamp());
            results.add(new Versioned<byte[]>(bodyPartBytes, clock));

        }

    } catch (MessagingException e) {
        throw new VoldemortException("Messaging exception while trying to parse GET response " + e.getMessage(),
                e);
    } catch (JsonParseException e) {
        throw new VoldemortException(
                "JSON parsing exception while trying to parse GET response " + e.getMessage(), e);
    } catch (JsonMappingException e) {
        throw new VoldemortException(
                "JSON mapping exception while trying to parse GET response " + e.getMessage(), e);
    } catch (IOException e) {
        throw new VoldemortException("IO exception while trying to parse GET response " + e.getMessage(), e);
    }
    return results;

}

From source file:sk.lazyman.gizmo.web.app.PageEmail.java

private Multipart createHtmlPart(String html) throws IOException, MessagingException {
    Multipart multipart = new MimeMultipart("related");

    BodyPart bodyPart = new MimeBodyPart();
    bodyPart.setDisposition(MimeMessage.INLINE);
    DataHandler dataHandler = new DataHandler(new ByteArrayDataSource(html, "text/html; charset=utf-8"));
    bodyPart.setDataHandler(dataHandler);
    multipart.addBodyPart(bodyPart);//from   w w  w.  java2 s. c om

    return multipart;
}

From source file:org.jahia.services.workflow.jbpm.JBPMMailProducer.java

protected void fillContent(Message email, Execution execution, JCRSessionWrapper session)
        throws MessagingException {
    String text = getTemplate().getText();
    String html = getTemplate().getHtml();
    List<AttachmentTemplate> attachmentTemplates = getTemplate().getAttachmentTemplates();

    try {//  ww  w .j  a  va 2  s  . co m
        if (html != null || !attachmentTemplates.isEmpty()) {
            // multipart
            MimeMultipart multipart = new MimeMultipart("related");

            BodyPart p = new MimeBodyPart();
            Multipart alternatives = new MimeMultipart("alternative");
            p.setContent(alternatives, "multipart/alternative");
            multipart.addBodyPart(p);

            // html
            if (html != null) {
                BodyPart htmlPart = new MimeBodyPart();
                html = evaluateExpression(execution, html, session);
                htmlPart.setContent(html, "text/html; charset=UTF-8");
                alternatives.addBodyPart(htmlPart);
            }

            // text
            if (text != null) {
                BodyPart textPart = new MimeBodyPart();
                text = evaluateExpression(execution, text, session);
                textPart.setContent(text, "text/plain; charset=UTF-8");
                alternatives.addBodyPart(textPart);
            }

            // attachments
            if (!attachmentTemplates.isEmpty()) {
                addAttachments(execution, multipart);
            }

            email.setContent(multipart);
        } else if (text != null) {
            // unipart
            text = evaluateExpression(execution, text, session);
            email.setText(text);
        }
    } catch (RepositoryException e) {
        logger.error(e.getMessage(), e);
    } catch (ScriptException e) {
        logger.error(e.getMessage(), e);
    }
}

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

/**
 * Creates a Multipart MIME Message (multiple content-types within the same message) from an existing mail
 * //from  w w w  .j  a  v  a  2 s. co  m
 * @param mail The original Mail
 * @return The Multipart MIME message
 */
public Multipart createMimeMultipart(Mail mail, XWikiContext context)
        throws MessagingException, XWikiException, IOException {
    Multipart multipart;
    List<Attachment> rawAttachments = mail.getAttachments() != null ? mail.getAttachments()
            : new ArrayList<Attachment>();

    if (mail.getHtmlPart() == null && mail.getAttachments() != null) {
        multipart = new MimeMultipart("mixed");

        // Create the text part of the email
        BodyPart textPart = new MimeBodyPart();
        textPart.setContent(mail.getTextPart(), "text/plain; charset=" + EMAIL_ENCODING);
        multipart.addBodyPart(textPart);

        // Add attachments to the main multipart
        for (Attachment attachment : rawAttachments) {
            multipart.addBodyPart(createAttachmentBodyPart(attachment, context));
        }
    } else {
        multipart = new MimeMultipart("mixed");
        List<Attachment> attachments = new ArrayList<Attachment>();
        List<Attachment> embeddedImages = new ArrayList<Attachment>();

        // Create the text part of the email
        BodyPart textPart;
        textPart = new MimeBodyPart();
        textPart.setText(mail.getTextPart());

        // Create the HTML part of the email, define the html as a multipart/related in case there are images
        Multipart htmlMultipart = new MimeMultipart("related");
        BodyPart htmlPart = new MimeBodyPart();
        htmlPart.setContent(mail.getHtmlPart(), "text/html; charset=" + EMAIL_ENCODING);
        htmlPart.setHeader("Content-Disposition", "inline");
        htmlPart.setHeader("Content-Transfer-Encoding", "quoted-printable");
        htmlMultipart.addBodyPart(htmlPart);

        // Find images used with src="cid:" in the email HTML part
        Pattern cidPattern = Pattern.compile("src=('|\")cid:([^'\"]*)('|\")",
                Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
        Matcher matcher = cidPattern.matcher(mail.getHtmlPart());
        List<String> foundEmbeddedImages = new ArrayList<String>();
        while (matcher.find()) {
            foundEmbeddedImages.add(matcher.group(2));
        }

        // Loop over the attachments of the email, add images used from the HTML to the list of attachments to be
        // embedded with the HTML part, add the other attachements to the list of attachments to be attached to the
        // email.
        for (Attachment attachment : rawAttachments) {
            if (foundEmbeddedImages.contains(attachment.getFilename())) {
                embeddedImages.add(attachment);
            } else {
                attachments.add(attachment);
            }
        }

        // Add the images to the HTML multipart (they should be hidden from the mail reader attachment list)
        for (Attachment image : embeddedImages) {
            htmlMultipart.addBodyPart(createAttachmentBodyPart(image, context));
        }

        // Wrap the HTML and text parts in an alternative body part and add it to the main multipart
        Multipart alternativePart = new MimeMultipart("alternative");
        BodyPart alternativeMultipartWrapper = new MimeBodyPart();
        BodyPart htmlMultipartWrapper = new MimeBodyPart();
        alternativePart.addBodyPart(textPart);
        htmlMultipartWrapper.setContent(htmlMultipart);
        alternativePart.addBodyPart(htmlMultipartWrapper);
        alternativeMultipartWrapper.setContent(alternativePart);
        multipart.addBodyPart(alternativeMultipartWrapper);

        // Add attachments to the main multipart
        for (Attachment attachment : attachments) {
            multipart.addBodyPart(createAttachmentBodyPart(attachment, context));
        }
    }

    return multipart;
}

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.j a  va 2  s  .  co  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:org.exoplatform.extension.social.notifications.SocialNotificationService.java

/**
 * /*from   ww  w . ja v  a2  s .  c  o m*/
 * @param space
 * @param managers
 * @param pendingUsers 
 */
private void pendingUserNotification(Space space, List<Profile> managerList, List<Profile> pendingUsers) {
    //TODO : use groovy template stored in JCR for mail information (cleaner, real templating)

    log.info("Sending mail to space manager : pending users");

    try {

        // loop on each manager and send mail
        // like that each manager will have the mail in its preferred language
        // ideally should be done in a different executor
        // TODO: see if we can optimize this to avoid do it for all user
        //       - send a mail to all the users in the same time (what about language)
        //       - cache the template result and send mail

        for (Profile manager : managerList) {
            Locale locale = Locale.getDefault();

            // get default locale of the manager
            String userId = manager.getIdentity().getRemoteId();
            String userLocale = this.getOrganizationService().getUserProfileHandler()
                    .findUserProfileByName(userId).getAttribute("user.language");
            if (userLocale != null && !userLocale.trim().isEmpty()) {
                locale = new Locale(userLocale);
            }

            // getMessageTemplate
            MessageTemplate messageTemplate = this.getMailMessageTemplate(
                    SocialNotificationConfiguration.MAIL_TEMPLATE_SPACE_PENDING_USERS, locale);

            GroovyTemplate g = new GroovyTemplate(messageTemplate.getSubject());

            String spaceUrl = this.getPortalUrl() + "/portal/g/:spaces:" + space.getUrl() + "/" + space.getUrl()
                    + "/settings"; //TODO: see which API to use
            String spaceAvatarUrl = null;
            if (space.getAvatarUrl() != null) {
                spaceAvatarUrl = this.getPortalUrl() + space.getAvatarUrl();
            }

            Map binding = new HashMap();
            binding.put("space", space);
            binding.put("portalUrl", this.getPortalUrl());
            binding.put("spaceSettingUrl", spaceUrl);
            binding.put("spaceAvatarUrl", spaceAvatarUrl);
            binding.put("userPendingList", pendingUsers);

            String subject = g.render(binding);

            g = new GroovyTemplate(messageTemplate.getHtmlContent());
            String htmlContent = g.render(binding);

            g = new GroovyTemplate(messageTemplate.getPlainTextContent());
            String textContent = g.render(binding);

            MailService mailService = this.getMailService();
            Session mailSession = mailService.getMailSession();
            MimeMessage message = new MimeMessage(mailSession);
            message.setFrom(this.getSenderAddress());

            // send email to manager
            message.setRecipient(RecipientType.TO,
                    new InternetAddress(manager.getEmail(), manager.getFullName()));
            message.setSubject(subject);
            MimeMultipart content = new MimeMultipart("alternative");
            MimeBodyPart text = new MimeBodyPart();
            MimeBodyPart html = new MimeBodyPart();
            text.setText(textContent);
            html.setContent(htmlContent, "text/html; charset=ISO-8859-1");
            content.addBodyPart(text);
            content.addBodyPart(html);
            message.setContent(content);

            log.info("Sending mail to" + manager.getEmail() + " : " + subject + " : " + subject + "\n" + html);

            //mailService.sendMessage(message);
        }

    } catch (Exception ex) {
        ex.printStackTrace();
    }
}