I have an emailService implementation in my Java Spring Boot project. To send email, I use JavaMailSender. In my service I need an access to HttpServletRequest and HttpServletResponse in order to instantiate WebContext. Now I am passing these 2 - request and response through my mailsender methods what sounds like a bad idea. I would like to have them in my service so I can call methods in my mailsender with only 2 variables: what email template to use and a map of variables that will be printed on that email. Is there a way to instantiate request and response in my service? Can I somehow autowire them in the service? Thats how my service looks like:
@Service
@Qualifier("MailSender")
public class MailSenderService {
@Autowired
private JavaMailSender mailSender;
@Autowired
private ServletContextTemplateResolver emailTemplateResolver;
public boolean sendMail(HttpServletRequest request, HttpServletResponse
response, HashMap<String, String> info, String template) throws
MessagingException, IOException{
final MimeMessage mimeMessage = this.mailSender.createMimeMessage();
final MimeMessageHelper message = new
MimeMessageHelper(mimeMessage,true, "UTF-8"); // true = multipart
message.setFrom("[email protected]");
message.setTo("[email protected]");
message.setSubject("This is the message subject");
TemplateEngine engine = new TemplateEngine();
engine.setTemplateResolver(emailTemplateResolver);
WebContext ctx = new WebContext(request, response,
request.getServletContext(), request.getLocale());
ctx.setVariable("info", info);
try{
String messageContent= engine.process(template, ctx);
mimeMessage.setContent(tt, "text/html; charset=utf-8");
}catch(Exception e){
e.printStackTrace();
}
this.mailSender.send(mimeMessage);
return true;
}
}
TemplateEnginebut simply configure that in your context (with the requiredTemplateResolvers) and inject it.TemplateEngineand just inject that instead ofServletContextTemplateResolver. YOu shouldn't bother with the configuration/setup in your mail sending class (it isn't its responsibility). Also you should be using a plainContextand not aWebContext.