1 package de.spring.webservices.rest.controller;
3 import java.time.OffsetDateTime;
4 import java.time.format.DateTimeFormatter;
5 import java.util.HashMap;
6 import java.util.Locale;
9 import javax.mail.MessagingException;
11 import org.slf4j.Logger;
12 import org.slf4j.LoggerFactory;
13 import org.springframework.beans.factory.annotation.Autowired;
14 import org.springframework.core.io.ClassPathResource;
15 import org.springframework.core.io.Resource;
16 import org.springframework.http.HttpStatus;
17 import org.springframework.web.bind.annotation.RequestMapping;
18 import org.springframework.web.bind.annotation.RequestMethod;
19 import org.springframework.web.bind.annotation.ResponseStatus;
20 import org.springframework.web.bind.annotation.RestController;
22 import de.spring.emails.services.EmailMakerService;
23 import de.spring.emails.services.EmailService;
26 @RequestMapping("/api/emails/")
27 public class EmailController {
28 private static final Logger LOGGER = LoggerFactory.getLogger(EmailController.class);
29 private static final String USER = "Gustavo Martin Morcuende";
30 private static final String USER_ADDRESS = "noemail@gumartinm.name";
31 private static final String TEMPLATE = "email-template";
32 private static final String LOGO = "logo";
33 private static final String LOGO_RESOURCE = "email/logo.png";
34 private static final String SUBJECT_MESSAGE_KEY = "email.subject";
36 private final EmailService emailService;
37 private final EmailMakerService emailMakerVelocityService;
40 public EmailController(EmailService emailService, EmailMakerService emailMakerVelocityService) {
41 this.emailService = emailService;
42 this.emailMakerVelocityService = emailMakerVelocityService;
45 @RequestMapping(method = RequestMethod.POST)
46 @ResponseStatus(HttpStatus.OK)
47 public void emails() throws MessagingException {
48 final String emailSubject = emailMakerVelocityService.getSubject(SUBJECT_MESSAGE_KEY, Locale.getDefault());
49 final String emailText = doEmailText();
50 final Map<String, Resource> inline = new HashMap<>();
51 inline.put(LOGO, new ClassPathResource(LOGO_RESOURCE));
52 final String[] to = { USER_ADDRESS };
55 emailService.sendEmailAsync(to, emailSubject, emailText, true, null, inline);
56 } catch (MessagingException ex) {
57 LOGGER.error("Send email error", ex);
61 private String doEmailText() {
62 final String isoDateTime = OffsetDateTime.now().format(DateTimeFormatter.ISO_OFFSET_DATE_TIME);
63 final Map<String, String> text = new HashMap<>();
64 text.put("user", USER);
65 text.put("date", isoDateTime);
67 return emailMakerVelocityService.emailMaker(text, TEMPLATE, Locale.getDefault());