Example usage for org.springframework.mail.javamail MimeMessageHelper setTo

List of usage examples for org.springframework.mail.javamail MimeMessageHelper setTo

Introduction

In this page you can find the example usage for org.springframework.mail.javamail MimeMessageHelper setTo.

Prototype

public void setTo(String[] to) throws MessagingException 

Source Link

Usage

From source file:org.jasig.portlet.blackboardvcportlet.service.impl.MailTemplateServiceImpl.java

public void sendMail(final MailTask mt) {
    try {//ww w. j  a  va  2 s  .c  o  m
        MimeMessagePreparator messagePreparator = new MimeMessagePreparator() {
            public void prepare(MimeMessage mimeMessage) throws Exception {
                MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true);

                if (mt.getMeetingInvite() != null) {
                    CalendarOutputter outputter = new CalendarOutputter();
                    ByteArrayOutputStream os = new ByteArrayOutputStream();
                    outputter.setValidating(false);
                    outputter.output(mt.getMeetingInvite(), os);

                    message.addAttachment("invite.ics", new ByteArrayResource(os.toByteArray()));
                }

                message.setFrom(mt.getFrom() != null ? mt.getFrom() : defaultFromAddress);

                if (mt.getTo() != null) {
                    String[] toArray = mt.getTo().toArray(new String[mt.getTo().size()]);
                    message.setTo(toArray);
                }
                if (mt.getSubject() != null) {
                    message.setSubject(mt.getSubject());
                } else {
                    switch (mt.getTemplate()) {
                    case MODERATOR:
                        message.setSubject(moderatorSubject);
                        break;
                    case INTERNAL_PARTICIPANT:
                        message.setSubject(internalParticipantSubject);
                        break;
                    case EXTERNAL_PARTICIPANT:
                        message.setSubject(externalParticipantSubject);
                        break;
                    case SESSION_DELETION:
                        message.setSubject(sessionDeletionSubject);
                        break;
                    default:
                        message.setSubject("");
                    }
                }

                message.setText(buildEmailMessage(mt), false);
            }
        };
        mailSender.send(messagePreparator);
    } catch (Exception e) {
        logger.error("Issue with sending email", e);
    }
}

From source file:com.seer.datacruncher.utils.mail.MailService.java

public void sendMail(MailConfig mailConfig) throws Exception {
    String logMsg = "MailService:sendMail():";
    InputStream attachment = null;
    MimeMessage mimeMessage = null;/*w  w  w .j  av a 2 s . com*/
    MimeMessageHelper helper = null;
    try {
        mimeMessage = mailSender.createMimeMessage();
        helper = new MimeMessageHelper(mimeMessage, true);
        helper.setText(mailConfig.getText(), true);
        if (StringUtils.isEmpty(mailConfig.getMailTo())) {
            log.error("Invalid or empty 'toAddress' configured!!");
            throw new Exception("Invalid or empty 'toAddress' configured");
        }
        if (StringUtils.isEmpty(mailConfig.getMailFrom())) {
            log.error("Invalid or empty 'FromAddress' configured!!");
            throw new Exception("Invalid or empty 'FromAddress' configured");
        }
        if (!isEmailValid(mailConfig.getMailFrom())) {
            log.error("Invalid 'FromAddress' configured!!");
            throw new Exception("Invalid 'FromAddress' configured");
        }
        helper.setFrom(new InternetAddress(mailConfig.getMailFrom()));
        helper.setSubject(mailConfig.getSubject());
        helper.setTo(getToAddress(mailConfig.getMailTo()));
        attachment = mailConfig.getAttachment();
        if (attachment != null) {
            StreamAttachmentDataSource datasource = new StreamAttachmentDataSource(mailConfig.getAttachment());
            helper.addAttachment(mailConfig.getAttachmentName(), datasource);
        }
        this.mailSender.send(mimeMessage);

    } catch (AuthenticationFailedException afex) {
        log.error(logMsg + "AuthenticationFailedException:", afex);
        throw new Exception("AuthenticationFailedException", afex);
    } catch (MessagingException mex) {
        log.error(logMsg + "Exception:", mex);
        throw new Exception("MessagingException", mex);
    } catch (Exception ex) {
        log.error(logMsg + "Exception:", ex);
        throw ex;
    }
}

From source file:MailSender.java

public void send(Item item) {

    // major: well, sender is null, so no email is going out...silently. Just a debug message.
    // this means that the initial configuration is not able to create a sender.
    // This control should no be here and the methods that handle jndi or configFile should throw a
    // ConfigurationException if the sender is not created.
    if (sender == null) {
        logger.debug("mail sender is null, not sending notifications");
        return;/*  w  ww  . jav  a 2  s . co m*/
    }

    // TODO make this locale sensitive per recipient
    // major: don't use the comment to explain what the code is doing, just wrap the function in a
    // method with a talking name. This apply to all comments in this method.
    logger.debug("attempting to send mail for item update");
    // prepare message content
    StringBuffer sb = new StringBuffer();
    String anchor = getItemViewAnchor(item, defaultLocale);
    sb.append(anchor);
    // minor: why is not important here the user's locale like in the sendUserPassword method?
    sb.append(ItemUtils.getAsHtml(item, messageSource, defaultLocale));
    sb.append(anchor);
    if (logger.isDebugEnabled()) {
        logger.debug("html content: " + sb);
    }
    // prepare message
    MimeMessage message = sender.createMimeMessage();
    // minor: I would use StandardCharsets.UTF_8.name() that return the canonical name
    // major: how do you test the use cases about the message?
    // the message is in the local stack so it can't be tested
    // better to implement a bridge pattern to decouple the messageHelper and pass it as
    // a collaborator. Although keep in mind that building the message is not a responsibility
    // of this class so this class should just send the message and not building it.
    MimeMessageHelper helper = new MimeMessageHelper(message, "UTF-8");

    // Remember the TO person email to prevent duplicate mails
    // minor: recipient would be a better name for this variable
    // major: catching a general Exception is a bad idea. You are telling me
    // we could have a problem but when I'm reading it and I don't understand
    // what could go wrong (and, also, the try block is too long so that's one of
    // the reason I can't see what could go wrong)
    String toPersonEmail;
    try {
        helper.setText(addHeaderAndFooter(sb), true);
        helper.setSubject(getSubject(item));
        helper.setSentDate(new Date());
        helper.setFrom(from);
        // set TO
        if (item.getAssignedTo() != null) {
            helper.setTo(item.getAssignedTo().getEmail());
            toPersonEmail = item.getAssignedTo().getEmail();
        } else {
            helper.setTo(item.getLoggedBy().getEmail());
            toPersonEmail = item.getLoggedBy().getEmail();
        }
        // set CC
        List<String> cclist = new ArrayList<String>();
        if (item.getItemUsers() != null) {
            for (ItemUser itemUser : item.getItemUsers()) {
                // Send only, if person is not the TO assignee
                if (!toPersonEmail.equals(itemUser.getUser().getEmail())) {
                    cclist.add(itemUser.getUser().getEmail());
                }
            }

            // sounds complicated but we have to ensure that no null
            // item will be set in setCC(). So we collect the cc items
            // in the cclist and transform it to an stringarray.
            if (cclist.size() > 0) {
                String[] cc = cclist.toArray(new String[0]);
                helper.setCc(cc);
            }
        }
        // send message
        // workaround: Some PSEUDO user has no email address. Because email
        // address
        // is mandatory, you can enter "no" in email address and the mail
        // will not
        // be sent.

        // major: this check is too late, we created everything and then we
        // won't use it.
        if (!"no".equals(toPersonEmail))
            sendInNewThread(message);
    } catch (Exception e) {
        logger.error("failed to prepare e-mail", e);
    }
}

From source file:com.mobileman.projecth.business.impl.MailManagerImpl.java

/** 
 * {@inheritDoc}/*ww w. jav a 2  s . c o m*/
 * @see com.mobileman.projecth.business.MailManager#sendTellAFriendMessage(java.lang.String, java.lang.String, java.lang.String, java.lang.String)
 */
@Override
public void sendTellAFriendMessage(final String senderName, final String senderEmail,
        final String receiverEmails, final String body) {
    if (log.isDebugEnabled()) {
        log.debug("sendMessage(" + senderName + ", " + senderEmail + ", " + receiverEmails + ", " + body
                + ") - start");
    }

    if (senderEmail == null || senderEmail.trim().length() == 0) {
        throw new MailException(MailException.Reason.SENDER_EMAIL_MISSING);
    }

    if (receiverEmails == null || receiverEmails.trim().length() == 0) {
        throw new MailException(MailException.Reason.SENDER_EMAIL_MISSING);
    }

    final String[] senderData = { "", "", "" };

    final String[] receivers = receiverEmails.split("[,]");
    for (int i = 0; i < receivers.length; i++) {
        final int idx = i;
        MimeMessagePreparator preparator = new MimeMessagePreparator() {

            /**
             * {@inheritDoc}
             * @see org.springframework.mail.javamail.MimeMessagePreparator#prepare(javax.mail.internet.MimeMessage)
             */
            @Override
            public void prepare(MimeMessage mimeMessage) throws Exception {
                if (log.isDebugEnabled()) {
                    log.debug("$MimeMessagePreparator.prepare(MimeMessage) - start"); //$NON-NLS-1$
                }

                MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true, EMAIL_ENCODING);
                messageHelper.setSentDate(new Date());

                Map<String, Object> model = new HashMap<String, Object>();
                model.put("body-text", body);
                String htmlMessage = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine,
                        "tell-a-friend-email-body.vm", model);
                String textMessage = HTMLTextParser.htmlToText(htmlMessage);
                messageHelper.setText(textMessage, htmlMessage);
                senderData[0] = htmlMessage;
                senderData[1] = textMessage;
                senderData[2] = "Mitteilung von projecth";

                messageHelper.setSubject(senderData[2]);
                messageHelper.setTo(receivers[idx]);
                messageHelper.setFrom(getSystemAdminEmail());

                if (log.isDebugEnabled()) {
                    log.debug("$MimeMessagePreparator.prepare(MimeMessage) - returns"); //$NON-NLS-1$
                }
            }
        };

        this.mailSender.send(preparator);
    }

    this.mailSender.send(new MimeMessagePreparator() {
        @Override
        public void prepare(MimeMessage mimeMessage) throws Exception {
            MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true, EMAIL_ENCODING);
            messageHelper.setSentDate(new Date());
            messageHelper.setText(senderData[1], senderData[0]);
            messageHelper.setSubject(senderData[2]);
            messageHelper.setTo(senderEmail);
            messageHelper.setFrom(getSystemAdminEmail());
        }
    });

    if (log.isDebugEnabled()) {
        log.debug("sendMessage(...) - end");
    }
}

From source file:gov.opm.scrd.batchprocessing.jobs.BatchProcessingJob.java

/**
 * Sends the notification by email.//from   www.  j a va2 s  .  c o  m
 * <p/>
 * This method does not throw any exception.
 *
 * @param mailMessage The message of the mail.
 * @param mailSubject The subject of the email.
 * @param processType The name of the current processor. It is used to distinguish the recipient of the email.
 */
private void notifyByEmail(String mailMessage, String mailSubject, String processType) {
    mailMessage = mailMessage.replace("@#$%EndingTime%$#@",
            DateFormat.getTimeInstance(DateFormat.LONG, Locale.US).format(new Date()));

    String recipient = processType.equals("BillProcessing") ? billMailRecipient : generalMailRecipient;

    logger.info(
            "Send email to " + recipient + ", subject = [" + mailSubject + "]. Message:" + CRLF + mailMessage);

    MimeMessage message = mailSender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(message);

    try {
        helper.setTo(recipient);

        helper.setSubject(mailSubject);

        helper.setText(mailMessage);

        mailSender.send(message);
    } catch (MessagingException e) {
        logger.error("Error sending email to " + recipient + ", subject = [" + mailSubject + "].", e);
    } catch (MailSendException e) {
        logger.error("Error sending email to " + recipient + ", subject = [" + mailSubject + "].", e);
    }
}

From source file:au.org.theark.core.service.ArkCommonServiceImpl.java

public void sendEmail(final SimpleMailMessage simpleMailMessage) throws MailSendException, VelocityException {
    MimeMessagePreparator preparator = new MimeMessagePreparator() {
        public void prepare(MimeMessage mimeMessage) throws Exception {
            MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
            message.setTo(simpleMailMessage.getTo());

            // The "from" field is required
            if (simpleMailMessage.getFrom() == null) {
                simpleMailMessage.setFrom(Constants.ARK_ADMIN_EMAIL);
            }/* w  w w . j a v a 2 s.  c  om*/

            message.setFrom(simpleMailMessage.getFrom());
            message.setSubject(simpleMailMessage.getSubject());

            // Map all the fields for the email template
            Map<String, Object> model = new HashMap<String, Object>();

            // Add the host name into the footer of the email
            String host = InetAddress.getLocalHost().getHostName();

            // Message title
            model.put("title", "Message from The ARK");
            // Message header
            model.put("header", "Message from The ARK");
            // Message subject
            model.put("subject", simpleMailMessage.getSubject());
            // Message text
            model.put("text", simpleMailMessage.getText());
            // Hostname in message footer
            model.put("host", host);

            // TODO: Add inline image(s)??
            // Add inline image header
            // FileSystemResource res = new FileSystemResource(new
            // File("c:/Sample.jpg"));
            // message.addInline("bgHeaderImg", res);

            // Set up the email text
            String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine,
                    "au/org/theark/core/velocity/resetPasswordEmail.vm", model);
            message.setText(text, true);
        }
    };

    // send out the email
    javaMailSender.send(preparator);
}

From source file:nl.strohalm.cyclos.utils.MailHandler.java

private void doSend(final String subject, final InternetAddress replyTo, final InternetAddress to,
        final String body, final boolean isHTML, final boolean throwException) {
    if (to == null || StringUtils.isEmpty(to.getAddress())) {
        return;//  ww w.j av  a2 s .  com
    }
    final LocalSettings localSettings = settingsService.getLocalSettings();
    final MailSettings mailSettings = settingsService.getMailSettings();
    final JavaMailSender mailSender = mailSettings.getMailSender();
    final MimeMessage message = mailSender.createMimeMessage();
    final MimeMessageHelper helper = new MimeMessageHelper(message, localSettings.getCharset());

    try {
        helper.setFrom(getSystemAddress());
        if (replyTo != null) {
            helper.setReplyTo(replyTo);
        }
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(body, isHTML);
        mailSender.send(message);
    } catch (final MessagingException e) {
        if (throwException) {
            throw new MailSendingException(subject, e);
        }
        // Store the current Exception
        CurrentTransactionData.setMailError(new MailSendingException(subject, e));
    } catch (final MailException e) {
        if (throwException) {
            throw new MailSendingException(subject, e);
        }
        CurrentTransactionData.setMailError(new MailSendingException(subject, e));
    }
}

From source file:ome.services.mail.MailUtil.java

/**
 * Main method which takes typical email fields as arguments, to prepare and
 * populate the given new MimeMessage instance and send.
 *
 * @param from//from www .  j a v a  2s .c  o  m
 *            email address message is sent from
 * @param to
 *            email address message is sent to
 * @param topic
 *            topic of the message
 * @param body
 *            body of the message
 * @param html
 *            flag determines the content type to apply.
 * @param ccrecipients
 *            list of email addresses message is sent as copy to
 * @param bccrecipients
 *            list of email addresses message is sent as blind copy to
 */
public void sendEmail(final String from, final String to, final String topic, final String body,
        final boolean html, final List<String> ccrecipients, final List<String> bccrecipients) {

    MimeMessagePreparator preparator = new MimeMessagePreparator() {
        public void prepare(MimeMessage mimeMessage) throws Exception {

            MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
            message.setText(body, html);
            message.setFrom(from);
            message.setSubject(topic);
            message.setTo(to);
            if (ccrecipients != null && !ccrecipients.isEmpty()) {
                message.setCc(ccrecipients.toArray(new String[ccrecipients.size()]));
            }

            if (bccrecipients != null && !bccrecipients.isEmpty()) {
                message.setCc(bccrecipients.toArray(new String[bccrecipients.size()]));
            }
        }

    };

    this.mailSender.send(preparator);
}

From source file:org.akaza.openclinica.control.core.SecureController.java

License:asdf

public Boolean sendEmail(String to, String from, String subject, String body, Boolean htmlEmail,
        String successMessage, String failMessage, Boolean sendMessage) throws Exception {
    Boolean messageSent = true;// w  ww.ja  v a  2s . c  o m
    try {
        JavaMailSenderImpl mailSender = (JavaMailSenderImpl) SpringServletAccess.getApplicationContext(context)
                .getBean("mailSender");
        // @pgawade 09-Feb-2012 #issue 13201 - setting the "mail.smtp.localhost" property to localhost when java API
        // is not able to
        // retrieve the host name
        Properties javaMailProperties = mailSender.getJavaMailProperties();
        if (null != javaMailProperties) {
            if (javaMailProperties.get("mail.smtp.localhost") == null
                    || ((String) javaMailProperties.get("mail.smtp.localhost")).equalsIgnoreCase("")) {
                javaMailProperties.put("mail.smtp.localhost", "localhost");
            }
        }

        MimeMessage mimeMessage = mailSender.createMimeMessage();

        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, htmlEmail);
        helper.setFrom(from);
        helper.setTo(processMultipleImailAddresses(to.trim()));
        helper.setSubject(subject);
        helper.setText(body, true);

        mailSender.send(mimeMessage);
        if (successMessage != null && sendMessage) {
            addPageMessage(successMessage);
        }
        logger.debug("Email sent successfully on {}", new Date());
    } catch (MailException me) {
        me.printStackTrace();
        if (failMessage != null && sendMessage) {
            addPageMessage(failMessage);
        }
        logger.debug("Email could not be sent on {} due to: {}", new Date(), me.toString());
        messageSent = false;
    }
    return messageSent;
}

From source file:org.akaza.openclinica.controller.SystemController.java

public String sendEmail(JavaMailSenderImpl mailSender, String emailSubject, String message)
        throws OpenClinicaSystemException {

    logger.info("Sending email...");
    try {/*from w  ww .  jav  a2  s.  com*/
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage);
        helper.setFrom(EmailEngine.getAdminEmail());
        helper.setTo("oc123@openclinica.com");
        helper.setSubject(emailSubject);
        helper.setText(message);

        mailSender.send(mimeMessage);
        return "ACTIVE";
    } catch (MailException me) {
        return "INACTIVE";
    } catch (MessagingException me) {
        return "INACTIVE";
    }
}