Example usage for org.springframework.mail SimpleMailMessage SimpleMailMessage

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

Introduction

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

Prototype

public SimpleMailMessage() 

Source Link

Document

Create a new SimpleMailMessage .

Usage

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  ww .j  a v 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: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);//  ww  w.  ja v a  2  s.  com
    mailMessage.setText(message);
    mailSender.send(mailMessage);
}

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

/**
 * Executes a shell script to send an email.
 *///  w  ww  .j av  a2s.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;
    }/* www.j  ava  2 s .  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:com.edgenius.wiki.gwt.server.SecurityControllerImpl.java

public int sendForgetPassword(String email) {
    User user = userReadingService.getUserByEmail(email);
    if (user == null) {
        //email does not exist
        return SharedConstants.RET_NO_EMAIL;
    }//  w  ww  .  j a v a 2 s  . c o m
    //reset this user password and send out
    String newPass = RandomStringUtils.randomAlphabetic(8);
    //so far, it is plain text - just for email body. It will be encrypted in UserSerivce.resetPassword()

    String plainPass = newPass;
    user.setPassword(newPass);
    //TODO: Does it need warranty only email send out, the password can be reset?
    //if so, I need change 2 things. Use mailEngine instead of mailService, change mailEngine throw exception 
    //rather than catch all Exception
    userService.resetPassword(user, newPass);
    //after above method, the password is encrypted one, so need keep plain one and send email

    //send email
    try {
        // Send create account email
        SimpleMailMessage msg = new SimpleMailMessage();
        msg.setFrom(Global.DefaultNotifyMail);
        msg.setTo(user.getContact().getEmail());

        Map<String, Object> map = new HashMap<String, Object>();
        map.put(WikiConstants.ATTR_PASSWORD, plainPass);
        map.put(WikiConstants.ATTR_USER, user);
        mailService.sendPlainMail(msg, WikiConstants.MAIL_TEMPL_FORGET_PASSWORD_NOTIFICATION, map);
        log.info("Email sent to " + user.getFullname() + " for password reset.");
    } catch (Exception e) {
        log.error("Failed to send reset passowrd email:" + user.getContact().getEmail(), e);
        return SharedConstants.RET_SEND_MAIL_FAILED;
    }

    return 0;
}

From source file:com.jrzmq.core.email.SimpleMailService.java

/**
 * ??//  w  w w . j  av  a2 s  .  c om
 * @param emailTo 
 * @param project 
 * @param ???
 * @param map     ?
 */
public void sendMail(String emailTo, String subject, String templateName, Map<String, Object> map) {
    SimpleMailMessage msg = new SimpleMailMessage();
    msg.setSentDate(new Date());
    msg.setTo(emailTo);
    msg.setSubject(subject);

    try {
        msg.setText(generateContent(templateName, map));
        mailSender.send(msg);
        if (logger.isInfoEnabled()) {
            logger.info("??{}", StringUtils.join(msg.getTo(), ","));
        }
    } catch (Exception e) {
        logger.error("??{},:{},", new Object[] { emailTo, subject }, e);
    }
}

From source file:com.netflix.genie.web.services.impl.MailServiceImpl.java

@Override
public void sendEmail(@NotBlank(message = "Cannot send email to blank address.") @Nonnull final String toEmail,
        @NotBlank(message = "Subject cannot be empty") @Nonnull final String subject,
        @Nullable final String body) throws GenieException {
    final SimpleMailMessage simpleMailMessage = new SimpleMailMessage();

    simpleMailMessage.setTo(toEmail);/*from   w  w w.j  a v  a2s . c  o  m*/
    simpleMailMessage.setFrom(this.fromAddress);
    simpleMailMessage.setSubject(subject);

    // check if body is not empty
    if (StringUtils.isNotBlank(body)) {
        simpleMailMessage.setText(body);
    }

    try {
        this.javaMailSender.send(simpleMailMessage);
    } catch (final MailException me) {
        throw new GenieServerException("Failure to send email", me);
    }
}

From source file:com.springsource.insight.plugin.mail.MessageSendOperationCollectionAspectTest.java

private void testSendMessage(int port) {
    JavaMailSenderImpl sender = new JavaMailSenderImpl();
    sender.setHost(NetworkAddressUtil.LOOPBACK_ADDRESS);
    sender.setProtocol(JavaMailSenderImpl.DEFAULT_PROTOCOL);
    sender.setPort(port);/*from  www. j  av  a2 s.  c  o  m*/

    SimpleMailMessage message = new SimpleMailMessage();
    message.setFrom("from@com.springsource.insight.plugin.mail");
    message.setTo("to@com.springsource.insight.plugin.mail");
    message.setCc("cc@com.springsource.insight.plugin.mail");
    message.setBcc("bcc@com.springsource.insight.plugin.mail");

    Date now = new Date(System.currentTimeMillis());
    message.setSentDate(now);
    message.setSubject(now.toString());
    message.setText("Test at " + now.toString());
    sender.send(message);

    Operation op = getLastEntered();
    assertNotNull("No operation extracted", op);
    assertEquals("Mismatched operation type", MailDefinitions.SEND_OPERATION, op.getType());
    assertEquals("Mismatched protocol", sender.getProtocol(),
            op.get(MailDefinitions.SEND_PROTOCOL, String.class));
    assertEquals("Mismatched host", sender.getHost(), op.get(MailDefinitions.SEND_HOST, String.class));
    if (port == -1) {
        assertEquals("Mismatched default port", 25, op.getInt(MailDefinitions.SEND_PORT, (-1)));
    } else {
        assertEquals("Mismatched send port", sender.getPort(), op.getInt(MailDefinitions.SEND_PORT, (-1)));
    }

    if (getAspect().collectExtraInformation()) {
        assertAddresses(op, MailDefinitions.SEND_SENDERS, 1);
        assertAddresses(op, MailDefinitions.SEND_RECIPS, 3);

        OperationMap details = op.get(MailDefinitions.SEND_DETAILS, OperationMap.class);
        assertNotNull("No details extracted", details);
        assertEquals("Mismatched subject", message.getSubject(),
                details.get(MailDefinitions.SEND_SUBJECT, String.class));
    }
}

From source file:com.springstudy.utils.email.SimpleMailService.java

/**
 * ??./* ww  w .  j  av  a 2  s  . com*/
 */
public boolean sendNotificationMail(com.gmk.framework.common.utils.email.Email email) {
    SimpleMailMessage msg = new SimpleMailMessage();
    msg.setFrom(Global.getConfig("mailFrom"));
    msg.setTo(email.getAddress());
    if (StringUtils.isNotEmpty(email.getCc())) {
        String cc[] = email.getCc().split(";");
        msg.setCc(cc);//?
    }
    msg.setSubject(email.getSubject());

    // ????
    //      String content = String.format(textTemplate, userName, new Date());
    String content = email.getContent();
    msg.setText(content);
    try {
        mailSender.send(msg);
        if (logger.isInfoEnabled()) {
            logger.info("??{}", StringUtils.join(msg.getTo(), ","));
        }
        return true;
    } catch (Exception e) {
        logger.error(email.getAddressee() + "-" + email.getSubject() + "-" + "??", e);
    }
    return false;
}

From source file:de.iteratec.iteraplan.businesslogic.service.notifications.NotificationServiceImpl.java

/** {@inheritDoc} */
public void sendEmail(Collection<User> users, String key, Map<User, EmailModel> emailModels) {
    if (sender == null || users == null) {
        return;/*  ww w .jav  a2  s . c om*/
    }

    if (StringUtils.isBlank(emailFrom)) {
        LOGGER.error("No outgoing email specified");
        throw new IteraplanTechnicalException(IteraplanErrorMessages.NOTIFICATION_CONFIGURATION_INCOMPLETE);
    }

    for (User user : users) {
        String emailTo = user.getEmail();

        if (StringUtils.isBlank(emailTo)) {
            LOGGER.error("Missing email address for user " + user.getLoginName());
            continue;
        }

        EmailModel model = emailModels.get(user);

        if (key.endsWith(".updated") && model.getChanges().isEmpty()) {
            continue;
        }

        Email email = null;
        try {
            email = emailFactory.createEmail(key, model);
        } catch (MailException e) {
            LOGGER.error("Error generating the email content: ", e);
            continue;
        }

        SimpleMailMessage message = new SimpleMailMessage();
        message.setTo(emailTo);
        message.setFrom(emailFrom);
        message.setSubject(email.getSubject());
        message.setText(email.getText());
        try {
            this.sender.send(message);
        } catch (MailException e) {
            LOGGER.error("Mail cannot be sent: ", e);
            continue;
        }
    }
}