0

I am new to Java Spring Boot - and I am trying to invoke a Mailer class to send out an email.

-- so at this forgot password stage - I reset the password and now I want to send the user their new password via email.

I've tried to do the following.

-- in my user handling controller

        //send
        MailService mailer = new MailService();
            mailer.sendEmail();

-- the mail service looks like this -- before there was a request mapping to send an email out when you went to /simpleemail.

package services;

import java.util.HashMap;
import java.util.Map;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Controller;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

//import org.apache.velocity.app.VelocityEngine;
import freemarker.template.Configuration;

@Controller
public class MailService {

    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    Configuration fmConfiguration;    

    /*
    @RequestMapping("/simpleemail")
    @ResponseBody
    String home() {
        try {
            sendEmail();
            return "Email Sent!";
        }catch(Exception ex) {
            return "Error in sending email: "+ex;
        }
    }*/

    public MailService(){

    }


    public void sendEmail() throws Exception{


        MimeMessage mimeMessage = mailSender.createMimeMessage();

        try {

            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);

            mimeMessageHelper.setSubject("Hi");
            mimeMessageHelper.setFrom("zzzz@gmail.com");
            mimeMessageHelper.setTo("xxxx@gmail.com");



            Map < String, Object > model = new HashMap < String, Object > ();
            model.put("firstName", "Yashwant");
            model.put("lastName", "Chavan");


            mimeMessageHelper.setText(geContentFromTemplate(model), true);

            mailSender.send(mimeMessageHelper.getMimeMessage());
        } catch (MessagingException e) {
            e.printStackTrace();
        }        


    }

    public String geContentFromTemplate(Map < String, Object > model) {
        StringBuffer content = new StringBuffer();

        try {
            content.append(FreeMarkerTemplateUtils
                .processTemplateIntoString(fmConfiguration.getTemplate("email-template.txt"), model));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return content.toString();
    }
}
Filburt
  • 17,626
  • 12
  • 64
  • 115
The Old County
  • 89
  • 13
  • 59
  • 129

0 Answers0