Example usage for javax.mail.internet MimeBodyPart setContent

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

Introduction

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

Prototype

@Override
public void setContent(Object o, String type) throws MessagingException 

Source Link

Document

A convenience method for setting this body part's content.

Usage

From source file:org.snopoke.util.Emailer.java

private MimeMultipart getCoverPart() throws MessagingException {
    // Alternative TEXT/HTML content
    MimeMultipart cover = new MimeMultipart("alternative");
    if (textContent != null && !textContent.isEmpty()) {
        MimeBodyPart text = new MimeBodyPart();
        cover.addBodyPart(text);//from   ww w. j  ava 2s  .  c  om
        text.setText(textContent);
    }

    if (htmlContent != null && !htmlContent.isEmpty()) {
        MimeBodyPart html = new MimeBodyPart();
        cover.addBodyPart(html);
        html.setContent(htmlContent, "text/html");
    }
    return cover;
}

From source file:org.exoplatform.extension.social.notifications.SocialNotificationService.java

/**
 * /* ww  w  .  j  av  a2 s .com*/
 * @param invitedUsersList 
 */
private void invitedUserNotification(Map<String, List<Space>> invitedUsersList) {

    for (Map.Entry<String, List<Space>> entry : invitedUsersList.entrySet()) {

        try {
            String userId = entry.getKey();
            List<Space> spacesList = entry.getValue();
            Locale locale = Locale.getDefault();

            // get default locale of the manager
            String userLocale = this.getOrganizationService().getUserProfileHandler()
                    .findUserProfileByName(userId).getAttribute("user.language");
            Profile userProfile = getIdentityManager()
                    .getOrCreateIdentity(OrganizationIdentityProvider.NAME, userId, false).getProfile();

            if (userLocale != null && !userLocale.trim().isEmpty()) {
                locale = new Locale(userLocale);
            }

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

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

            Map binding = new HashMap();
            binding.put("userProfile", userProfile);
            binding.put("portalUrl", this.getPortalUrl());
            binding.put("invitationUrl", this.getPortalUrl() + "/portal/intranet/invitationSpace");
            binding.put("spacesList", spacesList);

            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 invited user
            message.setRecipient(RecipientType.TO,
                    new InternetAddress(userProfile.getEmail(), userProfile.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 : " + userProfile.getEmail() + " : " + subject + "\n" + html);

            mailService.sendMessage(message);

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

}

From source file:org.apache.jsieve.mailet.SieveMailboxMailet.java

/**
 * Deliver the original mail as an attachment with the main part being an error report.
 *
 * @param recipient/*from  w  w w.  j a  va  2 s  .  c  o m*/
 * @param aMail
 * @param ex
 * @throws MessagingException
 * @throws IOException 
 */
protected void handleFailure(MailAddress recipient, Mail aMail, Exception ex)
        throws MessagingException, IOException {
    String user = getUsername(recipient);

    MimeMessage originalMessage = aMail.getMessage();
    MimeMessage message = new MimeMessage(originalMessage);
    MimeMultipart multipart = new MimeMultipart();

    MimeBodyPart noticePart = new MimeBodyPart();
    noticePart.setText(new StringBuilder().append(
            "An error was encountered while processing this mail with the active sieve script for user \"")
            .append(user).append("\". The error encountered was:\r\n").append(ex.getLocalizedMessage())
            .append("\r\n").toString());
    multipart.addBodyPart(noticePart);

    MimeBodyPart originalPart = new MimeBodyPart();
    originalPart.setContent(originalMessage, "message/rfc822");
    if ((originalMessage.getSubject() != null) && (!originalMessage.getSubject().trim().isEmpty())) {
        originalPart.setFileName(originalMessage.getSubject().trim());
    } else {
        originalPart.setFileName("No Subject");
    }
    originalPart.setDisposition(MimeBodyPart.INLINE);
    multipart.addBodyPart(originalPart);

    message.setContent(multipart);
    message.setSubject("[SIEVE ERROR] " + originalMessage.getSubject());
    message.setHeader("X-Priority", "1");
    message.saveChanges();

    storeMessageInbox(user, message);
}

From source file:org.openmrs.module.reporting.report.processor.EmailReportProcessor.java

/**
 * Performs some action on the given report
 * @param report the Report to process//from  w  w  w. j  a va2 s . c om
 */
public void process(Report report, Properties configuration) {

    try {
        Message m = new MimeMessage(getSession());

        m.setFrom(new InternetAddress(configuration.getProperty("from")));
        for (String recipient : configuration.getProperty("to", "").split("\\,")) {
            m.addRecipient(RecipientType.TO, new InternetAddress(recipient));
        }

        // TODO: Make these such that they can contain report information
        m.setSubject(configuration.getProperty("subject"));

        Multipart multipart = new MimeMultipart();

        MimeBodyPart contentBodyPart = new MimeBodyPart();
        String content = configuration.getProperty("content", "");
        if (report.getRenderedOutput() != null
                && "true".equalsIgnoreCase(configuration.getProperty("addOutputToContent"))) {
            content += new String(report.getRenderedOutput());
        }
        contentBodyPart.setContent(content, "text/html");
        multipart.addBodyPart(contentBodyPart);

        if (report.getRenderedOutput() != null
                && "true".equalsIgnoreCase(configuration.getProperty("addOutputAsAttachment"))) {
            MimeBodyPart attachment = new MimeBodyPart();
            Object output = report.getRenderedOutput();
            if (report.getOutputContentType().contains("text")) {
                output = new String(report.getRenderedOutput(), "UTF-8");
            }
            attachment.setDataHandler(new DataHandler(output, report.getOutputContentType()));
            attachment.setFileName(configuration.getProperty("attachmentName"));
            multipart.addBodyPart(attachment);
        }

        m.setContent(multipart);

        Transport.send(m);
    } catch (Exception e) {
        throw new RuntimeException("Error occurred while sending report over email", e);
    }
}

From source file:org.exoplatform.extension.social.notifications.SocialNotificationService.java

/**
 * /*from w  w  w. j av  a 2 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();
    }
}

From source file:org.sakaiproject.tool.assessment.util.SamigoEmailService.java

public String send() {
    List attachmentList = null;/*w w  w  .  j a  v a2s  .  com*/
    AttachmentData a = null;
    try {
        Properties props = new Properties();

        // Server
        if (smtpServer == null || smtpServer.equals("")) {
            log.info("samigo.email.smtpServer is not set");
            smtpServer = ServerConfigurationService.getString("smtp@org.sakaiproject.email.api.EmailService");
            if (smtpServer == null || smtpServer.equals("")) {
                log.info("smtp@org.sakaiproject.email.api.EmailService is not set");
                log.error(
                        "Please set the value of samigo.email.smtpServer or smtp@org.sakaiproject.email.api.EmailService");
                return "error";
            }
        }
        props.setProperty("mail.smtp.host", smtpServer);

        // Port
        if (smtpPort == null || smtpPort.equals("")) {
            log.warn("samigo.email.smtpPort is not set. The default port 25 will be used.");
        } else {
            props.setProperty("mail.smtp.port", smtpPort);
        }

        Session session;
        session = Session.getInstance(props);
        session.setDebug(true);
        MimeMessage msg = new MimeMessage(session);

        InternetAddress fromIA = new InternetAddress(fromEmailAddress, fromName);
        msg.setFrom(fromIA);
        InternetAddress[] toIA = { new InternetAddress(toEmailAddress, toName) };
        msg.setRecipients(Message.RecipientType.TO, toIA);

        if ("yes".equals(ccMe)) {
            InternetAddress[] ccIA = { new InternetAddress(fromEmailAddress, fromName) };
            msg.setRecipients(Message.RecipientType.CC, ccIA);
        }
        msg.setSubject(subject);

        EmailBean emailBean = (EmailBean) ContextUtil.lookupBean("email");
        attachmentList = emailBean.getAttachmentList();
        StringBuilder content = new StringBuilder(message);
        ArrayList fileList = new ArrayList();
        ArrayList fileNameList = new ArrayList();
        if (attachmentList != null) {
            if (prefixedPath == null || prefixedPath.equals("")) {
                log.error("samigo.email.prefixedPath is not set");
                return "error";
            }
            Iterator iter = attachmentList.iterator();
            while (iter.hasNext()) {
                a = (AttachmentData) iter.next();
                if (a.getIsLink().booleanValue()) {
                    log.debug("send(): url");
                    content.append("<br/>\n\r");
                    content.append("<br/>"); // give a new line
                    content.append(a.getFilename());
                } else {
                    log.debug("send(): file");
                    File attachedFile = getAttachedFile(a.getResourceId());
                    fileList.add(attachedFile);
                    fileNameList.add(a.getFilename());
                }
            }
        }

        Multipart multipart = new MimeMultipart();
        MimeBodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setContent(content.toString(), "text/html");
        multipart.addBodyPart(messageBodyPart);
        msg.setContent(multipart);

        for (int i = 0; i < fileList.size(); i++) {
            messageBodyPart = new MimeBodyPart();
            FileDataSource source = new FileDataSource((File) fileList.get(i));
            messageBodyPart.setDataHandler(new DataHandler(source));
            messageBodyPart.setFileName((String) fileNameList.get(i));
            multipart.addBodyPart(messageBodyPart);
        }
        msg.setContent(multipart);

        Transport.send(msg);
    } catch (UnsupportedEncodingException e) {
        log.error("Exception throws from send()" + e.getMessage());
        return "error";
    } catch (MessagingException e) {
        log.error("Exception throws from send()" + e.getMessage());
        return "error";
    } catch (ServerOverloadException e) {
        log.error("Exception throws from send()" + e.getMessage());
        return "error";
    } catch (PermissionException e) {
        log.error("Exception throws from send()" + e.getMessage());
        return "error";
    } catch (IdUnusedException e) {
        log.error("Exception throws from send()" + e.getMessage());
        return "error";
    } catch (TypeException e) {
        log.error("Exception throws from send()" + e.getMessage());
        return "error";
    } catch (IOException e) {
        log.error("Exception throws from send()" + e.getMessage());
        return "error";
    } finally {
        if (attachmentList != null) {
            if (prefixedPath != null && !prefixedPath.equals("")) {
                StringBuilder sbPrefixedPath;
                Iterator iter = attachmentList.iterator();
                while (iter.hasNext()) {
                    sbPrefixedPath = new StringBuilder(prefixedPath);
                    sbPrefixedPath.append("/email_tmp/");
                    a = (AttachmentData) iter.next();
                    if (!a.getIsLink().booleanValue()) {
                        deleteAttachedFile(sbPrefixedPath.append(a.getResourceId()).toString());
                    }
                }
            }
        }
    }
    return "send";
}

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

private Message buildMail(Session session) throws MessagingException, IOException {
    String subject = createSubject();
    Message mimeMessage = createMimeMessage(session, subject);
    mimeMessage.setDisposition(MimeMessage.INLINE);
    Multipart mp = new MimeMultipart("alternative");

    MimeBodyPart textBp = new MimeBodyPart();
    textBp.setDisposition(MimeMessage.INLINE);
    textBp.setContent("Please use mail client with HTML support.", "text/plain; charset=utf-8");
    mp.addBodyPart(textBp);//from w w  w .j ava  2 s  .c  om

    Multipart commentMultipart = null;
    EmailDto dto = model.getObject();
    if (StringUtils.isNotEmpty(dto.getBody())) {
        BodyPart bodyPart = new MimeBodyPart();
        bodyPart.setDisposition(MimeMessage.INLINE);
        DataHandler dataHandler = new DataHandler(
                new ByteArrayDataSource(dto.getBody(), "text/plain; charset=utf-8"));
        bodyPart.setDataHandler(dataHandler);

        commentMultipart = new MimeMultipart("mixed");
        commentMultipart.addBodyPart(bodyPart);
    }

    String html = createHtml();
    Multipart htmlMp = createHtmlPart(html);

    BodyPart htmlBp = new MimeBodyPart();
    htmlBp.setDisposition(BodyPart.INLINE);
    htmlBp.setContent(htmlMp);
    if (commentMultipart == null) {
        mp.addBodyPart(htmlBp);
    } else {
        commentMultipart.addBodyPart(htmlBp);
        BodyPart all = new MimeBodyPart();
        all.setDisposition(BodyPart.INLINE);
        all.setContent(commentMultipart);
        mp.addBodyPart(all);
    }
    mimeMessage.setContent(mp);

    return mimeMessage;
}

From source file:com.smartitengineering.emailq.service.impl.EmailServiceImpl.java

protected void sendEmail(Email email, List<Email> successfulEmails) {
    try {/*from  w ww  .  ja v  a  2s  .co  m*/
        if (logger.isDebugEnabled()) {
            logger.debug("Attempting to send " + email.getId() + " " + email.getSubject());
            if (email.getTo() != null) {
                logger.debug("To: " + Arrays.toString(email.getTo().toArray()));
            } else {
                logger.debug("To is NULL");
            }
            if (email.getTo() != null) {
                logger.debug("CC: " + Arrays.toString(email.getCc().toArray()));
            } else {
                logger.debug("CC is NULL");
            }
            if (email.getTo() != null) {
                logger.debug("BCC: " + Arrays.toString(email.getBcc().toArray()));
            } else {
                logger.debug("BCC is NULL");
            }
            if (email.getTo() != null) {
                logger.debug("FROM: " + email.getFrom());
            } else {
                logger.debug("FROM is NULL");
            }
            if (email.getAttachments() != null) {
                logger.debug("Attachments: " + Arrays.toString(email.getAttachments().toArray()));
                for (Attachments attachment : email.getAttachments()) {
                    logger.debug("Attachment: " + attachment.getName());
                }
            } else {
                logger.debug("No attachments");
            }
        }
        //Send email
        if (StringUtils.isBlank(email.getSubject()) || StringUtils.isBlank(email.getFrom())) {
            logger.warn(new StringBuilder("Invalid email without either from or a subject, thus ignoring it ")
                    .append(email.getId()).toString());
            return;
        }
        MimeMessage message = new MimeMessage(session);
        message.setSubject(email.getSubject());
        message.setFrom(new InternetAddress(email.getFrom()));
        addRecipients(message, Message.RecipientType.TO, email.getTo());
        addRecipients(message, Message.RecipientType.CC, email.getCc());
        addRecipients(message, Message.RecipientType.BCC, email.getBcc());
        if (email.getMessage() != null && StringUtils.isNotBlank(email.getMessage().getMsgBody())
                && email.getMessage().getMsgType().equals(MsgType.PLAIN)
                && (email.getAttachments() == null || email.getAttachments().isEmpty())) {
            message.setText(email.getMessage().getMsgBody());
        } else {
            Multipart multipart = new MimeMultipart();
            if (email.getMessage() != null && StringUtils.isNotBlank(email.getMessage().getMsgBody())) {
                MimeBodyPart bodyPart = new MimeBodyPart();
                switch (email.getMessage().getMsgType()) {
                case HTML:
                    bodyPart.setContent(email.getMessage().getMsgBody(), "html");
                    break;
                case PLAIN:
                default:
                    bodyPart.setText(email.getMessage().getMsgBody());
                }
                multipart.addBodyPart(bodyPart);
            }
            if (email.getAttachments() != null && !email.getAttachments().isEmpty()) {
                for (Attachments attachment : email.getAttachments()) {
                    addAttachment(multipart, attachment);
                }
            }
            message.setContent(multipart);
        }
        Transport.send(message);
        if (logger.isDebugEnabled()) {
            logger.debug("Sent " + email.getId());
        }
        //Update status
        email.setMailStatus(Email.MailStatus.SENT);
        successfulEmails.add(email);
        if (logger.isDebugEnabled()) {
            logger.debug("Set new mail status and add to successful queue " + email.getSubject());
        }
    } catch (Exception ex) {
        logger.warn(
                new StringBuilder("Error sending email with subject ").append(email.getSubject()).toString(),
                ex);
    }
}

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 ww  . j  ava2  s.  co  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.georchestra.ldapadmin.ws.emails.EmailController.java

/**
 * Send EmailEntry to smtp server//  w  w  w .  ja  va  2  s.c o m
 *
 * @param email email to send
 * @throws NameNotFoundException if recipient cannot be found in LDAP server
 * @throws DataServiceException if LDAP server is not available
 * @throws MessagingException if some field of email cannot be encoded (malformed email address)
 */
private void send(EmailEntry email) throws NameNotFoundException, DataServiceException, MessagingException {

    final Properties props = System.getProperties();
    props.put("mail.smtp.host", this.emailFactory.getSmtpHost());
    props.put("mail.protocol.port", this.emailFactory.getSmtpPort());

    final Session session = Session.getInstance(props, null);
    final MimeMessage message = new MimeMessage(session);

    Account recipient = this.accountDao.findByUID(email.getRecipient());
    InternetAddress[] senders = {
            new InternetAddress(this.accountDao.findByUID(email.getSender()).getEmail()) };

    message.addFrom(senders);
    message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient.getEmail()));
    message.setSubject(email.getSubject());
    message.setHeader("Date", (new MailDateFormat()).format(email.getDate()));

    // Mail content
    Multipart multiPart = new MimeMultipart("alternative");

    // attachments
    for (Attachment att : email.getAttachments()) {
        MimeBodyPart mbp = new MimeBodyPart();
        mbp.setDataHandler(new DataHandler(new ByteArrayDataSource(att.getContent(), att.getMimeType())));
        mbp.setFileName(att.getName());
        multiPart.addBodyPart(mbp);
    }

    // html part
    MimeBodyPart htmlPart = new MimeBodyPart();
    htmlPart.setContent(email.getBody(), "text/html; charset=utf-8");
    multiPart.addBodyPart(htmlPart);

    message.setContent(multiPart);

    // Send message
    Transport.send(message);
}