Example usage for javax.mail.internet MimeMessage setContent

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

Introduction

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

Prototype

@Override
public void setContent(Multipart mp) throws MessagingException 

Source Link

Document

This method sets the Message's content to a Multipart object.

Usage

From source file:nl.surfnet.coin.teams.control.DetailTeamController.java

/**
 * Notifies the user that requested to join a team that his request has been
 * declined//from   w  ww.  j a v  a  2s.c o m
 *
 * @param memberToAdd {@link Person} that wanted to join the team
 * @param team        {@link Team} he wanted to join
 * @param locale      {@link Locale}
 */
private void sendDeclineMail(final Person memberToAdd, final Team team, final Locale locale) {
    final String subject = messageSource.getMessage("request.mail.declined.subject", null, locale);
    final String html = composeDeclineMailMessage(team, locale, "html");
    final String plainText = composeDeclineMailMessage(team, locale, "plaintext");

    MimeMessagePreparator preparator = new MimeMessagePreparator() {
        public void prepare(MimeMessage mimeMessage) throws MessagingException {
            mimeMessage.addHeader("Precedence", "bulk");

            mimeMessage.setFrom(new InternetAddress(teamEnvironment.getSystemEmail()));
            mimeMessage.setRecipients(Message.RecipientType.TO, convertEmailAdresses(memberToAdd.getEmails()));
            mimeMessage.setSubject(subject);

            MimeMultipart rootMixedMultipart = controllerUtil.getMimeMultipartMessageBody(plainText, html);
            mimeMessage.setContent(rootMixedMultipart);
        }
    };

    mailService.sendAsync(preparator);
}

From source file:nl.surfnet.coin.teams.control.DetailTeamController.java

/**
 * Notifies the user that requested to join a team that his request has been
 * declined// w  w w  .  j  a  va 2s.c  o  m
 *
 * @param memberToAdd {@link Person} that wanted to join the team
 * @param team        {@link Team} he wanted to join
 * @param locale      {@link Locale}
 */
private void sendAcceptMail(final Person memberToAdd, final Team team, final Locale locale) {
    final String subject = messageSource.getMessage("request.mail.accepted.subject", null, locale);
    final String html = composeAcceptMailMessage(team, locale, "html");
    final String plainText = composeAcceptMailMessage(team, locale, "plaintext");

    MimeMessagePreparator preparator = new MimeMessagePreparator() {
        public void prepare(MimeMessage mimeMessage) throws MessagingException {
            mimeMessage.addHeader("Precedence", "bulk");

            mimeMessage.setFrom(new InternetAddress(teamEnvironment.getSystemEmail()));
            mimeMessage.setRecipients(Message.RecipientType.TO, convertEmailAdresses(memberToAdd.getEmails()));
            mimeMessage.setSubject(subject);

            MimeMultipart rootMixedMultipart = controllerUtil.getMimeMultipartMessageBody(plainText, html);
            mimeMessage.setContent(rootMixedMultipart);
        }
    };

    mailService.sendAsync(preparator);
}

From source file:eagle.common.email.EagleMailClient.java

private boolean _send(String from, String to, String cc, String title, String content,
        List<MimeBodyPart> attachments) {
    MimeMessage mail = new MimeMessage(session);
    try {//from  w w  w . j av  a 2  s  . c om
        mail.setFrom(new InternetAddress(from));
        mail.setSubject(title);
        if (to != null) {
            mail.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
        }
        if (cc != null) {
            mail.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc));
        }

        //mail.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(DEFAULT_BCC_ADDRESS));

        MimeBodyPart mimeBodyPart = new MimeBodyPart();
        mimeBodyPart.setContent(content, "text/html;charset=utf-8");

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

        for (MimeBodyPart attachment : attachments) {
            multipart.addBodyPart(attachment);
        }

        mail.setContent(multipart);
        //         mail.setContent(content, "text/html;charset=utf-8");
        LOG.info(String.format("Going to send mail: from[%s], to[%s], cc[%s], title[%s]", from, to, cc, title));
        Transport.send(mail);
        return true;
    } catch (AddressException e) {
        LOG.info("Send mail failed, got an AddressException: " + e.getMessage(), e);
        return false;
    } catch (MessagingException e) {
        LOG.info("Send mail failed, got an AddressException: " + e.getMessage(), e);
        return false;
    }
}

From source file:ro.agrade.jira.qanda.listeners.DirectEmailMessageHandler.java

@Override
protected void sendMail(String[] recipients, String subject, String message, String from)
        throws MessagingException {

    SMTPMailServer server = mailServerManager.getDefaultSMTPMailServer();
    if (server == null) {
        LOG.debug("Email server is not configured. QandA is unable to send mails ...");
        return;//from   w ww  .  j a v  a2s  . c o m
    }
    LOG.debug("Email message: initializing.");
    //Set the host smtp address
    Properties props = new Properties();

    String proto = server.getMailProtocol().getProtocol();

    props.put("mail.transport.protocol", proto);
    props.put("mail." + proto + ".host", server.getHostname());
    props.put("mail." + proto + ".port", server.getPort());

    String username = server.getUsername();
    String password = server.getPassword();

    Authenticator auth = null;

    if (username != null && password != null) {
        auth = new SMTPAuthenticator(username, password);
        props.put("mail." + proto + ".auth", "true");
    }
    Session session;
    try {
        session = auth != null ? Session.getDefaultInstance(props, auth) : Session.getDefaultInstance(props);
    } catch (SecurityException ex) {
        LOG.warn("Could not get default session. Attempting to create a new one.");
        session = auth != null ? Session.getInstance(props, auth) : Session.getInstance(props);
    }

    // create a message
    MimeMessage msg = new MimeMessage(session);
    Multipart multipart = new MimeMultipart();

    if (from == null) {
        from = server.getDefaultFrom();
    }
    // set the from address
    if (from != null) {
        InternetAddress addressFrom = new InternetAddress(from);
        msg.setFrom(addressFrom);
    }

    if (recipients != null && recipients.length > 0) {
        // set TO address(es)
        InternetAddress[] addressTo = new InternetAddress[recipients.length];
        for (int i = 0; i < recipients.length; i++) {
            addressTo[i] = new InternetAddress(recipients[i]);
        }
        msg.setRecipients(Message.RecipientType.TO, addressTo);
    }

    // Setting the Subject
    msg.setSubject(subject);

    // Setting text content
    MimeBodyPart contentPart = new MimeBodyPart();
    contentPart.setContent(message, "text/html; charset=utf-8");
    multipart.addBodyPart(contentPart);

    msg.setContent(multipart);
    Transport.send(msg);
    LOG.debug("Email message sent successfully.");
}

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

/**
 * //ww w  .j a  v a 2 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.exoplatform.extension.social.notifications.SocialNotificationService.java

/**
 * /*from  w  w w.  jav  a  2 s .  c om*/
 * @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:com.reizes.shiva.net.mail.Mail.java

public void sendHtmlMail(String fromName, String from, String to, String cc, String bcc, String subject,
        String content) throws UnsupportedEncodingException, MessagingException {
    boolean parseStrict = false;
    MimeMessage message = new MimeMessage(getSessoin());
    InternetAddress address = InternetAddress.parse(from, parseStrict)[0];

    if (fromName != null) {
        address.setPersonal(fromName, charset);
    }/*from  w  w w.  java2 s.  c o m*/

    message.setFrom(address);

    message.setRecipients(Message.RecipientType.TO, parseAddresses(to));

    if (cc != null) {
        message.setRecipients(Message.RecipientType.CC, parseAddresses(cc));
    }
    if (bcc != null) {
        message.setRecipients(Message.RecipientType.BCC, parseAddresses(bcc));
    }

    message.setSubject(subject, charset);

    message.setHeader("X-Mailer", "sendMessage");
    message.setSentDate(new java.util.Date()); //   

    Multipart multipart = new MimeMultipart();
    MimeBodyPart bodypart = new MimeBodyPart();
    bodypart.setContent(content, "text/html; charset=" + charset);
    multipart.addBodyPart(bodypart);

    message.setContent(multipart);
    Transport.send(message);
}

From source file:com.mgmtp.jfunk.core.reporting.EmailReporter.java

private void sendMessage(final String content) {
    try {/*w  w  w.ja v a2 s  .  c o  m*/
        MimeMessage msg = new MimeMessage(sessionProvider.get());
        msg.setSubject("jFunk E-mail Report");
        msg.addRecipients(Message.RecipientType.TO, recipientsProvider.get());

        BodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setContent(content, "text/html; charset=UTF-8");

        MimeMultipart multipart = new MimeMultipart("related");
        multipart.addBodyPart(messageBodyPart);

        messageBodyPart = new MimeBodyPart();
        messageBodyPart.setDataHandler(new DataHandler(getClass().getResource("check.gif")));
        messageBodyPart.setHeader("Content-ID", "<check>");
        multipart.addBodyPart(messageBodyPart);

        messageBodyPart = new MimeBodyPart();
        messageBodyPart.setDataHandler(new DataHandler(getClass().getResource("error.gif")));
        messageBodyPart.setHeader("Content-ID", "<error>");
        multipart.addBodyPart(messageBodyPart);

        msg.setContent(multipart);

        smtpClientProvider.get().send(msg);

        int anzahlRecipients = msg.getAllRecipients().length;
        log.info(
                "Report e-mail was sent to " + anzahlRecipients + " recipient(s): " + recipientsProvider.get());
    } catch (MessagingException e) {
        log.error("Error while creating report e-mail", e);
    } catch (MailException e) {
        log.error("Error while sending report e-mail", e);
    }
}

From source file:fr.hoteia.qalingo.core.util.impl.MimeMessagePreparatorImpl.java

public void prepare(MimeMessage message) throws Exception {

    // AUTO unsubscribe for Gmail/Hotmail etc : RFC2369
    if (StringUtils.isNotEmpty(getUnsubscribeUrlOrEmail())) {
        message.addHeader("List-Unsubscribe", "<" + getUnsubscribeUrlOrEmail() + ">");
    }//  w  ww  .j av  a 2 s .  c  o m

    if (getFrom() != null) {
        List<InternetAddress> toAddress = new ArrayList<InternetAddress>();
        toAddress.add(new InternetAddress(getFrom(), getFromName()));
        message.addFrom(toAddress.toArray(new InternetAddress[toAddress.size()]));
    }
    if (getTo() != null) {
        message.addRecipients(Message.RecipientType.TO, InternetAddress.parse(getTo()));
    }
    if (getCc() != null) {
        message.addRecipients(Message.RecipientType.CC, InternetAddress.parse(getCc()));
    }
    if (getSubject() != null) {
        message.setSubject(getSubject());
    }

    MimeMultipart mimeMultipart = new MimeMultipart("alternative");// multipart/mixed or mixed or related or alternative
    message.setContent(mimeMultipart);

    if (getPlainTextContent() != null) {
        BodyPart textBodyPart = new MimeBodyPart();
        textBodyPart.setContent(getPlainTextContent(), "text/plain");
        mimeMultipart.addBodyPart(textBodyPart);
    }

    if (getHtmlContent() != null) {
        BodyPart htmlBodyPart = new MimeBodyPart();
        htmlBodyPart.setContent(getHtmlContent(), "text/html");
        mimeMultipart.addBodyPart(htmlBodyPart);
    }

}

From source file:net.duckling.ddl.service.mail.impl.MailServiceImpl.java

public void sendMail(Mail mail) {
    LOG.debug("sendEmail() to: " + mail.getRecipient());
    try {/*from   w  ww.j  av  a  2 s . c  om*/
        Session session = Session.getInstance(m_bag.m_mailProperties, m_bag.m_authenticator);
        session.setDebug(false);
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(m_bag.m_fromAddress);
        msg.setRecipient(Message.RecipientType.TO, new InternetAddress(mail.getRecipient()));
        msg.setSubject(mail.getSubject());
        msg.setSentDate(new Date());

        Multipart mp = new MimeMultipart();

        MimeBodyPart txtmbp = new MimeBodyPart();
        txtmbp.setContent(mail.getMessage(), EMAIL_CONTENT_TYPE);
        mp.addBodyPart(txtmbp);

        List<String> attachments = mail.getAttachments();
        for (Iterator<String> it = attachments.iterator(); it.hasNext();) {
            MimeBodyPart mbp = new MimeBodyPart();
            String filename = it.next();
            FileDataSource fds = new FileDataSource(filename);
            mbp.setDataHandler(new DataHandler(fds));
            mbp.setFileName(MimeUtility.encodeText(fds.getName()));
            mp.addBodyPart(mbp);
        }

        msg.setContent(mp);

        if ((m_bag.m_fromAddress != null) && (m_bag.m_fromAddress.getAddress() != null)
                && (m_bag.m_fromAddress.getAddress().indexOf("@") != -1)) {
            cheat(msg,
                    m_bag.m_fromAddress.getAddress().substring(m_bag.m_fromAddress.getAddress().indexOf("@")));
        }

        Transport.send(msg);

        LOG.info("Successfully send the mail to " + mail.getRecipient());

    } catch (Throwable e) {

        LOG.error("Exception occured while trying to send notification to: " + mail.getRecipient(), e);
        LOG.debug("Details:", e);
    }
}