Example usage for org.springframework.mail SimpleMailMessage setFrom

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

Introduction

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

Prototype

@Override
    public void setFrom(String from) 

Source Link

Usage

From source file:com.gnizr.web.action.user.ApproveUserAccount.java

private boolean sendNotificationEmail(User user) {
    Map<String, Object> model = new HashMap<String, Object>();
    model.put("token", token);
    model.put("username", user.getUsername());
    model.put("email", user.getEmail());
    model.put("createdOn", user.getCreatedOn());
    model.put("gnizrConfiguration", getGnizrConfiguration());

    if (getWelcomeEmailTemplate() == null) {
        logger.error("ApproveUserAccount: welcomeEmailTemplate bean is not defined");
        addActionError(String.valueOf(ActionErrorCode.ERROR_CONFIG));
        return false;
    }/*  ww w . j a  va2s.  com*/

    String toUserEmail = user.getEmail();
    if (toUserEmail == null) {
        logger.error("ApproveUserAccount: the email of user " + user.getUsername() + " is not defined");
        addActionError(String.valueOf(ActionErrorCode.ERROR_EMAIL_UNDEF));
        return false;
    }

    SimpleMailMessage notifyMsg = new SimpleMailMessage(getWelcomeEmailTemplate());
    notifyMsg.setTo(toUserEmail);

    if (notifyMsg.getFrom() == null) {
        String contactEmail = getGnizrConfiguration().getSiteContactEmail();
        if (contactEmail != null) {
            notifyMsg.setFrom(contactEmail);
        } else {
            notifyMsg.setFrom("no-reply@localhost");
        }
    }

    Template fmTemplate1 = null;
    String text1 = null;
    try {
        fmTemplate1 = freemarkerEngine.getTemplate("login/welcome-template.ftl");
        text1 = FreeMarkerTemplateUtils.processTemplateIntoString(fmTemplate1, model);
    } catch (Exception e) {
        logger.error("ApproveUserAccount: error creating message template from Freemarker engine");
    }
    notifyMsg.setText(text1);

    if (getMailSender() == null) {
        logger.error("ApproveUserAccount: mailSender bean is not defined");
        addActionError(String.valueOf(ActionErrorCode.ERROR_CONFIG));
        return false;
    }
    try {
        getMailSender().send(notifyMsg);
        return true;
    } catch (Exception e) {
        logger.error("ApproveUserAccount: send mail error. " + e);
        addActionError(String.valueOf(ActionErrorCode.ERROR_INTERNAL));
    }

    return false;
}

From source file:burstcoin.observer.service.NetworkService.java

private void sendMessage(String subject, String message) {
    SimpleMailMessage mailMessage = new SimpleMailMessage();
    mailMessage.setTo(ObserverProperties.getMailReceiver());
    mailMessage.setReplyTo(ObserverProperties.getMailReplyTo());
    mailMessage.setFrom(ObserverProperties.getMailSender());
    mailMessage.setSubject(subject);/*from   w  w w . ja  v  a 2 s.  co m*/
    mailMessage.setText(message);
    mailSender.send(mailMessage);
}

From source file:org.openxdata.server.servlet.ResetPasswordServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter out = response.getWriter();

    WebApplicationContext ctx = WebApplicationContextUtils
            .getRequiredWebApplicationContext(this.getServletContext());
    mailSender = (org.springframework.mail.javamail.JavaMailSenderImpl) ctx.getBean("mailSender");
    userService = (UserService) ctx.getBean("userService");
    userDetailsService = (UserDetailsService) ctx.getBean("userDetailsService");
    messageSource = (ResourceBundleMessageSource) ctx.getBean("messageSource");
    userLocale = new Locale((String) request.getSession().getAttribute("locale")); //new AcceptHeaderLocaleResolver().resolveLocale(request);
    log.debug("userLocale=" + userLocale.getLanguage());

    String email = request.getParameter("email");
    if (email == null) {
        //ajax response reference text
        out.println("noEmailSuppliedError");
    }//from www .  j a  v a 2 s . co  m

    try {
        User user = userService.findUserByEmail(email);
        /*
          * Valid User with the correct e-mail.
          */
        insertUserInSecurityContext(user); // this is so that it is possible to reset their password (security checks)

        Properties props = propertyPlaceholder.getResolvedProps();
        String from = props.getProperty("mailSender.from");

        try {
            //Reset the User password and send an email
            userService.resetPassword(user, 6);
            SimpleMailMessage msg = new SimpleMailMessage();
            msg.setTo(email);
            msg.setSubject(messageSource.getMessage("resetPasswordEmailSubject",
                    new Object[] { user.getFullName() }, userLocale));
            msg.setText(messageSource.getMessage("resetPasswordEmail",
                    new Object[] { user.getName(), user.getClearTextPassword() }, userLocale));
            msg.setFrom(from);

            try {
                mailSender.send(msg);
                //ajax response reference text
                out.println("passwordResetSuccessful");
            } catch (MailException ex) {
                log.error("Error while sending an email to the user " + user.getName()
                        + " in order to reset their password.", ex);
                log.error("Password reset email:" + msg.toString());
                //ajax response reference text
                out.println("emailSendError");
            }
        } catch (Exception e) {
            log.error("Error while resetting the user " + user.getName() + "'s password", e);
            //ajax response reference text
            out.println("passwordResetError");
        }
    } catch (UserNotFoundException userNotFound) {
        /*
        * Invalid User or incorrect Email.
        */
        //ajax response reference text
        out.println("validationError");
    }
}

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

/**
 * Send an email message for this {@link IReminder}.
 * //from  w  ww.  j  a  va 2  s. c o  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);
    }
}

From source file:com.gnizr.web.action.user.RegisterUser.java

private boolean sendEmailVerification(String token, User user) {
    Map<String, Object> model = new HashMap<String, Object>();
    model.put("token", token);
    model.put("username", user.getUsername());
    model.put("gnizrConfiguration", getGnizrConfiguration());

    if (getVerifyEmailTemplate() == null) {
        logger.error("RegisterUser: templateMessge bean is not defined");
        addActionError(String.valueOf(ActionErrorCode.ERROR_CONFIG));
        return false;
    }//from   w ww  .  j  av  a  2 s  .  co  m
    String toEmail = user.getEmail();
    if (toEmail == null) {
        logger.error("RegisterUser: the email of user " + user.getUsername() + " is not defined");
        addActionError(String.valueOf(ActionErrorCode.ERROR_EMAIL_UNDEF));
        return false;
    }
    SimpleMailMessage msg = new SimpleMailMessage(getVerifyEmailTemplate());
    msg.setTo(toEmail);

    if (msg.getFrom() == null) {
        String contactEmail = getGnizrConfiguration().getSiteContactEmail();
        if (contactEmail != null) {
            msg.setFrom(contactEmail);
        } else {
            msg.setFrom("help@localhost");
        }
    }

    Template fmTemplate = null;
    String text = null;
    try {
        fmTemplate = freemarkerEngine.getTemplate("login/verifyemail-template.ftl");
        text = FreeMarkerTemplateUtils.processTemplateIntoString(fmTemplate, model);
    } catch (Exception e) {
        logger.error("RegisterUser: error creating message template from Freemarker engine");
    }

    msg.setText(text);

    if (getMailSender() == null) {
        logger.error("RegisterUser: mailSender bean is not defined");
        addActionError(String.valueOf(ActionErrorCode.ERROR_CONFIG));
        return false;
    }
    try {
        getMailSender().send(msg);
        return true;
    } catch (Exception e) {
        logger.error("RegisterUser: send mail error. " + e);
        addActionError(String.valueOf(ActionErrorCode.ERROR_INTERNAL));
    }
    return false;
}

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  w w.  j  ava2s. c  om*/
    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:com.gnizr.web.action.user.RegisterUser.java

private boolean sendNotifyAndApproval(String token, User user) {
    Map<String, Object> model = new HashMap<String, Object>();
    model.put("token", token);
    model.put("username", user.getUsername());
    model.put("email", user.getEmail());
    model.put("createdOn", user.getCreatedOn());
    model.put("gnizrConfiguration", getGnizrConfiguration());

    if (getNotifyEmailTemplate() == null) {
        logger.error("RegisterUser: notifyEmailTemplate bean is not defined");
        addActionError(String.valueOf(ActionErrorCode.ERROR_CONFIG));
        return false;
    }/*ww  w.j  av a2 s .c o  m*/
    if (getApprovalEmailTemplate() == null) {
        logger.error("RegisterUser: approvalEmailTemplate bean is not defined");
        addActionError(String.valueOf(ActionErrorCode.ERROR_CONFIG));
        return false;
    }

    String toUserEmail = user.getEmail();
    String toAppvEmail = getGnizrConfiguration().getSiteContactEmail();
    if (toUserEmail == null) {
        logger.error("RegisterUser: the email of user " + user.getUsername() + " is not defined");
        addActionError(String.valueOf(ActionErrorCode.ERROR_EMAIL_UNDEF));
        return false;
    }

    SimpleMailMessage notifyMsg = new SimpleMailMessage(getNotifyEmailTemplate());
    notifyMsg.setTo(toUserEmail);

    if (notifyMsg.getFrom() == null) {
        String contactEmail = getGnizrConfiguration().getSiteContactEmail();
        if (contactEmail != null) {
            notifyMsg.setFrom(contactEmail);
        } else {
            notifyMsg.setFrom("no-reply@localhost");
        }
    }

    SimpleMailMessage approvalMsg = new SimpleMailMessage(getApprovalEmailTemplate());
    if (toAppvEmail != null) {
        approvalMsg.setTo(toAppvEmail);
        approvalMsg.setFrom(toUserEmail);
    } else {
        logger.error("RegisterUser: siteContactEmail is not defined. Can't sent approval emaili. Abort.");
        return false;
    }

    Template fmTemplate1 = null;
    Template fmTemplate2 = null;
    String text1 = null;
    String text2 = null;
    try {
        fmTemplate1 = freemarkerEngine.getTemplate("login/notifyemail-template.ftl");
        fmTemplate2 = freemarkerEngine.getTemplate("login/approvalemail-template.ftl");
        text1 = FreeMarkerTemplateUtils.processTemplateIntoString(fmTemplate1, model);
        text2 = FreeMarkerTemplateUtils.processTemplateIntoString(fmTemplate2, model);
    } catch (Exception e) {
        logger.error("RegisterUser: error creating message template from Freemarker engine");
    }
    notifyMsg.setText(text1);
    approvalMsg.setText(text2);

    if (getMailSender() == null) {
        logger.error("RegisterUser: mailSender bean is not defined");
        addActionError(String.valueOf(ActionErrorCode.ERROR_CONFIG));
        return false;
    }
    try {
        getMailSender().send(notifyMsg);
        getMailSender().send(approvalMsg);
        return true;
    } catch (Exception e) {
        logger.error("RegisterUser: send mail error. " + e);
        addActionError(String.valueOf(ActionErrorCode.ERROR_INTERNAL));
    }

    return false;
}

From source file:net.solarnetwork.central.dras.biz.alert.SimpleAlertBiz.java

private boolean handleAlert(final User user, final Alert alert, final String subject, final String message,
        final Long creatorId) {
    List<UserContact> contacts = user.getContactInfo();
    if (contacts == null) {
        return false;
    }/* w ww  .  j a  va 2s  .co m*/

    // get the user's preferred contact method
    UserContact contact = null;
    for (UserContact aContact : contacts) {
        if (aContact.getPriority() == null) {
            continue;
        }
        if (contact == null || (aContact.getPriority() < contact.getPriority())) {
            contact = aContact;
        }
    }
    if (contact == null) {
        log.debug("User {} has no preferred contact method, not sending alert {}", user.getUsername(),
                alert.getAlertType());
        return false;
    }

    // send the user an alert... only email supported currently
    SimpleMailMessage msg = new SimpleMailMessage();
    msg.setTo(contact.getContact());
    msg.setText(message);
    switch (contact.getKind()) {
    case MOBILE:
        // treat as an email to their mobile number
        // TODO: extract out mobile SMS handling to configurable service
        msg.setTo(contact.getContact().replaceAll("\\D", "") + "@isms.net.nz");
        msg.setFrom("escalation@econz.co.nz");

        break;

    case EMAIL:
        msg.setSubject(subject);
        msg.setFrom("solar-adr@solarnetwork.net");
        break;

    default:
        log.debug("User {} contact type {} not supported in alerts", user.getUsername(), contact.getKind());
        return false;
    }
    sendMailMessage(msg, creatorId);
    return true;
}

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

/**
 * Executes a shell script to send an email.
 *//*from  w ww.  j a  v a  2s . c  o 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 void makeFriendsWithSpaceGroups(String spaceUname, List<String> roleNameList) {
    if (roleNameList == null || roleNameList.size() == 0) {
        log.info("No new role updated in given input.");
        return;// w ww  .  ja v a 2 s.co m
    }

    //skip all non-space role, such as system role
    for (Iterator<String> iter = roleNameList.iterator(); iter.hasNext();) {
        String roleName = iter.next();
        if (!roleName.startsWith(Role.SPACE_ROLE_PREFIX))
            iter.remove();
    }
    if (roleNameList.size() == 0) {
        log.info("All roles is system role, no need continue to check friendship.");
        return;
    }

    //get all available roles(type must be ROLE.TYPE_SPACE) for this space currently.
    List<String> availRoleList = new ArrayList<String>();
    Resource res = resourceDAO.getByName(spaceUname);
    Set<Permission> perms = res.getPermissions();
    if (perms != null) {
        for (Permission perm : perms) {
            Set<Role> roles = perm.getRoles();
            if (roles != null) {
                for (Role role : roles) {
                    if (role.getType() != Role.TYPE_SPACE)
                        continue;
                    availRoleList.add(role.getName());
                }
            }

        }
    }

    //filter out which role is new added
    List<String> newRoleList = new ArrayList<String>();
    for (String name : roleNameList) {
        boolean found = false;
        for (String exist : availRoleList) {
            if (StringUtils.equalsIgnoreCase(exist, name)) {
                found = true;
                break;
            }
        }
        if (!found) {
            newRoleList.add(name);
        }
    }
    if (newRoleList.size() == 0) {
        log.info("Given new role list does not contain any new added role for space " + spaceUname);
    } else {
        //OK, find new added role for this space. check if it is in friends list already
        int prefixLen = Role.SPACE_ROLE_PREFIX.length();
        for (String newSpace : newRoleList) {
            //get space name from 
            newSpace = newSpace.substring(prefixLen);
            Friend frd = friendDAO.getFriendship(Friend.PREFIX_SPACE + spaceUname,
                    Friend.PREFIX_SPACE + newSpace);
            if (frd != null && frd.isConfirmed()) {
                continue;
            }
            if (frd == null) {
                //CREATE Pending friendship
                frd = new Friend();
                frd.setSender(Friend.PREFIX_SPACE + spaceUname);
                frd.setReceiver(Friend.PREFIX_SPACE + newSpace);
                WikiUtil.setTouchedInfo(userReadingService, frd);
                frd.setStatus(Friend.STATUS_PENDING);
                friendDAO.saveOrUpdate(frd);

                //send message
                String text = "Space " + spaceUname + " adds your space " + newSpace + " on its friend list.";
                //                     "{action:id="+rejectFriendship+ "|title=reject|confirmMessage=Do you want to reject this request?|" +
                //                     "sender="+spaceUname+"|receiver="+newSpace
                //                     +"} or {action:id="+acceptFriendship+"|title=accept|confirmMessage=Do you want to accept this request?|" +
                //                     "sender="+spaceUname+"|receiver="+newSpace+"}";

                notificationService.sendMessage(text, SharedConstants.MSG_TARGET_SPACE_ADMIN_ONLY, newSpace,
                        NotificationService.SEND_MAIL_ONLY_HAS_RECEIVERS);

                //send request email
                Set<String> userMails = userReadingService.getSpaceAdminMailList(newSpace);
                for (String mail : userMails) {
                    try {
                        SimpleMailMessage msg = new SimpleMailMessage();
                        msg.setFrom(Global.DefaultNotifyMail);
                        Map<String, Object> map = new HashMap<String, Object>();
                        map.put("sender", spaceUname);
                        map.put("receiver", newSpace);
                        map.put(WikiConstants.ATTR_PAGE_LINK,
                                WebUtil.getHostAppURL() + "invite!friendship.do?sender="
                                        + URLEncoder.encode(spaceUname, Constants.UTF8) + "&receiver="
                                        + URLEncoder.encode(newSpace, Constants.UTF8));
                        msg.setTo(mail);
                        mailService.sendPlainMail(msg, WikiConstants.MAIL_TEMPL_FRIENDSHIP, map);
                    } catch (Exception e) {
                        log.error("Failed send friendship email:" + mail, e);
                    }
                }

            }
            //reject,pending do nothing
        }
    }

}