Example usage for org.springframework.mail SimpleMailMessage setTo

List of usage examples for org.springframework.mail SimpleMailMessage setTo

Introduction

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

Prototype

@Override
    public void setTo(String... to) 

Source Link

Usage

From source file:cz.muni.fi.mir.services.MailServiceImpl.java

@Override
public void sendMail(String from, String receiver, String subject, String message)
        throws IllegalArgumentException {
    if (isEnabled()) {
        if (StringUtils.isEmpty(receiver)) {
            throw new IllegalArgumentException("Receiver of email is not set. to value is [" + receiver + "]");
        }/*w  w w.j a  v a  2s. com*/
        if (StringUtils.isEmpty(subject)) {
            throw new IllegalArgumentException(
                    "Subject of email is not set. subject value is [" + subject + "]");
        }
        if (StringUtils.isEmpty(message)) {
            throw new IllegalArgumentException(
                    "Message of email is not set. message value is [" + message + "]");
        }

        SimpleMailMessage mailMessage = new SimpleMailMessage();

        if (StringUtils.isEmpty(from)) {
            mailMessage.setFrom(sender);
        } else {
            mailMessage.setFrom(from);
        }

        if (StringUtils.isEmpty(subjectPrefix)) {
            mailMessage.setSubject(subjectPrefix + subject);
        } else {
            mailMessage.setSubject(subject);
        }
        mailMessage.setTo(receiver);
        mailMessage.setText(message);

        mailSender.send(mailMessage);
    }
}

From source file:nz.net.orcon.kanban.automation.actions.EmailSenderAction.java

public void sendSecureEmail(String subject, String emailBody, String to, String bcc, String from,
        String replyTo, String host, String password) {

    SimpleMailMessage mailMessage = new SimpleMailMessage();
    JavaMailSenderImpl mailSender = new JavaMailSenderImpl();

    mailSender.setHost(host);//from w ww.j  a  v  a2  s.  c o  m
    mailSender.setPort(587);
    mailSender.setProtocol("smtp");

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

    mailSender.setJavaMailProperties(props);

    if (StringUtils.isNotBlank(to)) {
        mailMessage.setTo(to);
    }
    if (StringUtils.isNotBlank(bcc)) {
        mailMessage.setBcc(bcc);
    }

    if (StringUtils.isNotBlank(from)) {
        mailMessage.setFrom(from);
        mailSender.setUsername(from);
    }

    if (StringUtils.isNotBlank(password)) {
        mailSender.setPassword(password);
    }

    if (StringUtils.isNotBlank(replyTo)) {
        mailMessage.setReplyTo(replyTo);
    }

    if (StringUtils.isNotBlank(subject)) {
        mailMessage.setSubject(subject);
    }

    mailMessage.setText(emailBody);
    mailSender.send(mailMessage);
    logger.info("Secure Email Message has been sent..");
}

From source file:csns.util.EmailUtils.java

public boolean sendTextMail(Email email) {
    SimpleMailMessage message = new SimpleMailMessage();
    message.setSubject(email.getSubject());
    message.setText(getText(email));// w ww.  ja v a2s.co m
    message.setFrom(email.getAuthor().getPrimaryEmail());
    message.setCc(email.getAuthor().getPrimaryEmail());
    String addresses[] = getAddresses(email.getRecipients(), email.isUseSecondaryEmail())
            .toArray(new String[0]);
    if (addresses.length > 1) {
        message.setTo(appEmail);
        message.setBcc(addresses);
    } else
        message.setTo(addresses);

    mailSender.send(message);

    logger.info(email.getAuthor().getUsername() + " sent email to "
            + StringUtils.arrayToCommaDelimitedString(addresses));

    return true;
}

From source file:com.healthcit.cacure.utils.MailSendingService.java

/**
 * Sends a notification email, that a section has been submitted for review
 *
 * @param form the form, which is submitted for review
 * @param toEmail the recipient - the intended recipients are ROLE_APPROVERs
 *///from   www  . j a  v  a 2s .  com
public void sendSubmittedSectionNotification(QuestionnaireForm form, String toEmail, String webAppUri) {
    SimpleMailMessage message = new SimpleMailMessage(submittedSectionNotificationTemplate);

    StringBuilder emailText = new StringBuilder(submittedSectionNotificationTemplate.getText());
    //TODO: DEVISE A BETTER WAY OF OBTAINING THE WEB-APP PATH
    StringUtils.replace(emailText, WEB_APP_PATH_IDENTIFIER, webAppUri);
    StringUtils.replace(emailText, MODULE_ID_IDENTIFIER, form.getModule().getId().toString());
    StringUtils.replace(emailText, FORM_ID_IDENTIFIER, form.getId().toString());

    message.setText(emailText.toString());
    message.setTo(toEmail);

    try {
        if (logger.isDebugEnabled()) {
            logger.debug("Sending section submitted notification mail to " + toEmail);
        }

        mailSender.send(message);

    } catch (MailException me) {
        logger.error("Failed sending section submitted notification mail", me);
    }
}

From source file:edu.wisc.jmeter.MonitorListener.java

/**
 * Executes a shell script to send an email.
 *//* ww  w .j a v  a  2s . co  m*/
private void sendEmail(Date now, String subject, String body, String host, Status status) {
    log("Sending email (" + status + "): " + subject + " - " + body);

    final SimpleMailMessage message = new SimpleMailMessage();
    message.setTo(emailTo);
    message.setFrom(emailFrom);
    message.setSubject(subject);
    message.setText(body);

    try {
        this.javaMailSender.send(message);
    } catch (MailException me) {
        log("Failed to send email", me);
    }
}

From source file:com.edgenius.wiki.service.impl.FriendServiceImpl.java

public List<String> sendInvitation(User sender, String spaceUname, String toEmailGroup, String message) {

    String[] emails = toEmailGroup.split("[;,]");
    //check email, and only save valid email to database
    if (emails == null || emails.length == 0) {
        //no valid email address
        return null;
    }//from   w ww  .j  a va  2s  .c  o m
    List<String> validEmails = new ArrayList<String>();
    for (String email : emails) {
        email = email.trim();
        if (email.matches(
                "^[a-zA-Z0-9][\\w\\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\\w\\.-]*[a-zA-Z0-9]\\.[a-zA-Z][a-zA-Z\\.]*[a-zA-Z]$")) {
            validEmails.add(email);
        } else {
            log.warn("Invalid email in friend invite email group, this email will be ignore:" + email);
        }
    }
    if (validEmails.size() == 0) {
        //no valid email address
        log.warn("Email group does not include invalid email, invitation cancelled: " + toEmailGroup);
        return null;
    }
    Invitation invite = new Invitation();
    invite.setCreatedDate(new Date());
    invite.setCreator(sender);

    invite.setMessage(message);
    invite.setSpaceUname(spaceUname);
    invite.setUuid(RandomStringUtils.randomAlphanumeric(WikiConstants.UUID_KEY_SIZE).toLowerCase());

    //send mail
    Space space = spaceService.getSpaceByUname(spaceUname);
    message = StringUtils.isBlank(message) ? messageService.getMessage(WikiConstants.I18N_INVITE_MESSAGE)
            : message;
    Map<String, Object> map = new HashMap<String, Object>();
    map.put(WikiConstants.ATTR_USER, sender);
    map.put(WikiConstants.ATTR_SPACE, space);

    map.put(WikiConstants.ATTR_INVITE_MESSAGE, message);
    //space home page
    String url = WikiUtil.getPageRedirFullURL(spaceUname, null, null);
    map.put(WikiConstants.ATTR_PAGE_LINK, url);

    List<String> validGroup = new ArrayList<String>();
    for (String email : validEmails) {
        try {
            if (Global.hasSuppress(SUPPRESS.SIGNUP)) {
                User user = userReadingService.getUserByEmail(email);
                if (user == null) {
                    //only unregistered user to be told system is not allow sign-up
                    map.put(WikiConstants.ATTR_SIGNUP_SUPRESSED, true);
                } else {
                    map.put(WikiConstants.ATTR_SIGNUP_SUPRESSED, false);
                }
            } else {
                map.put(WikiConstants.ATTR_SIGNUP_SUPRESSED, false);
            }

            map.put(WikiConstants.ATTR_INVITE_URL, WebUtil.getHostAppURL() + "invite.do?s="
                    + URLEncoder.encode(spaceUname, Constants.UTF8) + "&i=" + invite.getUuid());
            SimpleMailMessage msg = new SimpleMailMessage();
            msg.setFrom(Global.DefaultNotifyMail);
            msg.setTo(email);
            mailService.sendPlainMail(msg, WikiConstants.MAIL_TEMPL_INVITE, map);
            validGroup.add(email);
        } catch (Exception e) {
            log.error("Failed send email to invite " + email, e);
        }
    }
    invite.setToEmailGroup(StringUtils.join(validGroup, ','));
    invitationDAO.saveOrUpdate(invite);

    //if system public signup is disabled, then here need check if that invited users are register users, if not, here need send email to notice system admin to add those users.
    if (Global.hasSuppress(SUPPRESS.SIGNUP)) {
        List<String> unregistereddEmails = new ArrayList<String>();
        for (String email : validGroup) {
            User user = userReadingService.getUserByEmail(email);
            if (user == null) {
                unregistereddEmails.add(email);
            }
        }

        if (!unregistereddEmails.isEmpty()) {
            //send email to system admin.
            map = new HashMap<String, Object>();
            map.put(WikiConstants.ATTR_USER, sender);
            map.put(WikiConstants.ATTR_SPACE, space);
            map.put(WikiConstants.ATTR_LIST, unregistereddEmails);
            mailService.sendPlainToSystemAdmins(WikiConstants.MAIL_TEMPL_ADD_INVITED_USER, map);
        }
    }
    return validGroup;
}

From source file:org.jasig.schedassist.impl.events.AutomaticAppointmentCancellationApplicationListener.java

@Async
@Override/*www. jav  a2 s  . c o m*/
public void onApplicationEvent(AutomaticAppointmentCancellationEvent event) {
    ICalendarAccount owner = event.getOwner();
    VEvent vevent = event.getEvent();

    deleteEventReminder(owner, vevent);

    PropertyList attendeeList = vevent.getProperties(Attendee.ATTENDEE);

    SimpleMailMessage message = new SimpleMailMessage();
    List<String> recipients = new ArrayList<String>();
    for (Object o : attendeeList) {
        Property attendee = (Property) o;
        String value = attendee.getValue();
        String email = value.substring(EmailNotificationApplicationListener.MAILTO_PREFIX.length());
        if (EmailNotificationApplicationListener.isEmailAddressValid(email)) {
            recipients.add(email);
        } else {
            LOG.debug("skipping invalid email: " + email);
        }
    }
    message.setTo(recipients.toArray(new String[] {}));

    if (!EmailNotificationApplicationListener.isEmailAddressValid(owner.getEmailAddress())) {
        message.setFrom(noReplyFromAddress);
    } else {
        message.setFrom(owner.getEmailAddress());
    }
    message.setSubject(vevent.getSummary().getValue() + " has been cancelled");
    message.setText(constructMessageBody(vevent, event.getReason(), owner.getDisplayName()));

    LOG.debug("sending message: " + message.toString());
    mailSender.send(message);
    LOG.debug("message successfully sent");
}

From source file:com.edgenius.wiki.service.impl.NotifyMQConsumer.java

/**
 * @param msg/*from   w w  w.  ja v a 2 s . co m*/
 * @param bccList
 * @param model
 */
private void sendMail(String templName, Collection<String> bccList, Map<String, Object> model) {

    SimpleMailMessage msg = new SimpleMailMessage();
    //So far don't user setBcc(bccList) to all user since if one of them mail address is bad, it may cause 
    //al emails can not be send.
    for (String bcc : bccList) {
        //because message "TO" user can not be blank, so here just add default mail address but add 
        //the really recipient on BCC in order to hide user private email info.
        msg.setTo(bcc);
        msg.setFrom(Global.DefaultNotifyMail);
        try {
            //whatever error happen, go on to next user
            mailEngine.sendPlainMail(msg, templName, model);
        } catch (Throwable e) {
            log.error("Send Page Notify mail failed to " + bcc + ". ", e);
        }
    }
    log.info("Email sent to " + bccList.size() + " users.");
}

From source file:com.traffitruck.web.HtmlController.java

@RequestMapping(value = "/forgotPassword", method = RequestMethod.POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
ModelAndView forgotPassword(@RequestParam("username") String username) {
    if (username != null) {
        LoadsUser loadsUser = dao.getUser(username);
        if (loadsUser != null) {
            Random random = new Random();
            StringBuilder newPassword = new StringBuilder();
            for (int i = 0; i < 8; ++i)
                newPassword.append(random.nextInt(10));
            Map<String, Object> model = new HashMap<>();
            model.put("email", loadsUser.getEmail());
            ResetPassword rp = new ResetPassword();
            rp.setCreationDate(new Date());
            rp.setUsername(username);//from w  w  w  .  j  av a  2 s.  co m
            rp.setUuid(String.valueOf(newPassword));
            dao.newResetPassword(rp);
            SimpleMailMessage msg = new SimpleMailMessage();
            msg.setTo(loadsUser.getEmail());
            msg.setSubject("forgot password");
            msg.setFrom("no-reply@traffitruck.com");
            String message = "   ?   ?-\n"
                    + "?? ?  ? ?  ? ?  \n"
                    + "   ?- ? " + newPassword + "\n"
                    + "   15 \n"
                    + " ?     \n";

            msg.setText(message);
            mailSender.send(msg);
            return new ModelAndView("forgot_password_explain", model);
        }
    }
    Map<String, Object> model = new HashMap<>();
    model.put("error", "notfound");
    return new ModelAndView("forgot_password", model);
}

From source file:org.jasig.schedassist.impl.reminder.DefaultReminderServiceImpl.java

/**
 * Send an email message for this {@link IReminder}.
 * /*w w  w  .j  av a2  s  . co m*/
 * @param reminder
 */
protected void sendEmail(IReminder reminder) {
    if (shouldSend(reminder)) {
        final IScheduleOwner owner = reminder.getScheduleOwner();
        final ICalendarAccount recipient = reminder.getRecipient();
        final VEvent event = reminder.getEvent();
        Reminders reminderPrefs = owner.getRemindersPreference();
        final boolean includeOwner = reminderPrefs.isIncludeOwner();

        SimpleMailMessage message = new SimpleMailMessage();
        final boolean canSendToOwner = emailAddressValidator.canSendToEmailAddress(owner.getCalendarAccount());
        if (canSendToOwner) {
            message.setFrom(owner.getCalendarAccount().getEmailAddress());
        } else {
            message.setFrom(noReplyFromAddress);
        }

        if (includeOwner && canSendToOwner) {
            message.setTo(
                    new String[] { owner.getCalendarAccount().getEmailAddress(), recipient.getEmailAddress() });
        } else {
            message.setTo(new String[] { recipient.getEmailAddress() });
        }

        message.setSubject("Reminder: " + event.getSummary().getValue());
        final String messageBody = createMessageBody(event, owner);
        message.setText(messageBody);

        LOG.debug("sending message: " + message.toString());
        try {
            mailSender.send(message);
            LOG.debug("message successfully sent");
        } catch (MailSendException e) {
            LOG.error("caught MailSendException for " + owner + ", " + recipient + ", " + reminder, e);
        }

    } else {
        LOG.debug("skipping sendEmail for reminder that should not be sent: " + reminder);
    }
}