Skip to content

Commit c1411e9

Browse files
authored
Merge pull request eugenp#542 from oreva/master
Spring MVC Email application added.
2 parents 3daf23a + 5744df6 commit c1411e9

14 files changed

Lines changed: 583 additions & 0 deletions

File tree

‎spring-mvc-email/README.md‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
## Spring MVC Email
2+
3+
Example Spring MVC project to send email from web form.
4+
5+
### Installing and Running
6+
7+
Just run the Spring Boot application.
8+
Type http://localhost:8080 in your browser to open the application.
9+
10+
11+
### Sending test emails
12+
13+
Follow UI links to send simple email, email using template or email with attachment.

‎spring-mvc-email/pom.xml‎

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3+
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4+
<modelVersion>4.0.0</modelVersion>
5+
6+
<groupId>org.baeldung.spring</groupId>
7+
<artifactId>SpringMVCEmail</artifactId>
8+
<version>1.0</version>
9+
<packaging>war</packaging>
10+
11+
<parent>
12+
<groupId>org.springframework.boot</groupId>
13+
<artifactId>spring-boot-starter-parent</artifactId>
14+
<version>1.4.0.RELEASE</version>
15+
<relativePath></relativePath>
16+
</parent>
17+
18+
<dependencies>
19+
<dependency>
20+
<groupId>org.springframework.boot</groupId>
21+
<artifactId>spring-boot-starter-web</artifactId>
22+
</dependency>
23+
<!-- Spring Boot Starter Mail dependency -->
24+
<dependency>
25+
<groupId>org.springframework.boot</groupId>
26+
<artifactId>spring-boot-starter-mail</artifactId>
27+
<version>1.4.0.RELEASE</version>
28+
</dependency>
29+
<!-- The following two dependencies included to render jsp pages -->
30+
<dependency>
31+
<groupId>org.apache.tomcat.embed</groupId>
32+
<artifactId>tomcat-embed-jasper</artifactId>
33+
<version>8.5.4</version>
34+
</dependency>
35+
<dependency>
36+
<groupId>javax.servlet</groupId>
37+
<artifactId>jstl</artifactId>
38+
<version>1.2</version>
39+
</dependency>
40+
</dependencies>
41+
42+
<properties>
43+
<java.version>1.8</java.version>
44+
</properties>
45+
46+
47+
<build>
48+
<plugins>
49+
<plugin>
50+
<groupId>org.springframework.boot</groupId>
51+
<artifactId>spring-boot-maven-plugin</artifactId>
52+
</plugin>
53+
</plugins>
54+
</build>
55+
</project>
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
package com.baeldung.spring;
2+
3+
import org.springframework.boot.SpringApplication;
4+
import org.springframework.boot.autoconfigure.SpringBootApplication;
5+
6+
7+
@SpringBootApplication
8+
public class Application {
9+
public static void main(String[] args) {
10+
SpringApplication.run(Application.class, args);
11+
}
12+
}
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
package com.baeldung.spring.app.config;
2+
3+
import org.springframework.context.annotation.Bean;
4+
import org.springframework.context.annotation.ComponentScan;
5+
import org.springframework.context.annotation.Configuration;
6+
import org.springframework.mail.SimpleMailMessage;
7+
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
8+
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
9+
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
10+
import org.springframework.web.servlet.view.InternalResourceViewResolver;
11+
import org.springframework.web.servlet.view.JstlView;
12+
import org.springframework.web.servlet.view.UrlBasedViewResolver;
13+
14+
/**
15+
* Created with IntelliJ IDEA.
16+
* User: Olga
17+
*/
18+
@Configuration
19+
@ComponentScan("com.baeldung.spring")
20+
@EnableWebMvc //tha same as <mvc:annotation-driven/>
21+
public class AppConfig extends WebMvcConfigurerAdapter {
22+
@Override
23+
public void addResourceHandlers(ResourceHandlerRegistry registry) {
24+
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
25+
}
26+
27+
@Bean
28+
public UrlBasedViewResolver urlBasedViewResolver() {
29+
UrlBasedViewResolver resolver = new UrlBasedViewResolver();
30+
resolver.setOrder(0);
31+
resolver.setPrefix("/WEB-INF/views/");
32+
resolver.setSuffix(".jsp");
33+
resolver.setCache(false);
34+
resolver.setViewClass(JstlView.class);
35+
return resolver;
36+
}
37+
38+
@Bean
39+
public InternalResourceViewResolver internalResourceViewResolver() {
40+
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
41+
resolver.setOrder(1);
42+
resolver.setPrefix("/WEB-INF/views/");
43+
resolver.setSuffix(".jsp");
44+
resolver.setViewClass(JstlView.class);
45+
return resolver;
46+
}
47+
48+
@Bean
49+
public SimpleMailMessage templateSimpleMessage() {
50+
SimpleMailMessage message = new SimpleMailMessage();
51+
message.setText("This is the test email template for your email:\n%s\n");
52+
return message;
53+
}
54+
}
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
package com.baeldung.spring.controllers;
2+
3+
import org.springframework.stereotype.Controller;
4+
import org.springframework.web.bind.annotation.RequestMapping;
5+
import org.springframework.web.bind.annotation.RequestMethod;
6+
7+
/**
8+
* Created with IntelliJ IDEA.
9+
* User: Olga
10+
*/
11+
@Controller
12+
@RequestMapping({"/","/home"})
13+
public class HomeController {
14+
15+
@RequestMapping(method = RequestMethod.GET)
16+
public String showHomePage() {
17+
return "home";
18+
}
19+
}
Lines changed: 131 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,131 @@
1+
package com.baeldung.spring.controllers;
2+
3+
import com.baeldung.spring.mail.EmailServiceImpl;
4+
import com.baeldung.spring.web.dto.MailObject;
5+
import org.springframework.beans.factory.annotation.Autowired;
6+
import org.springframework.beans.factory.annotation.Qualifier;
7+
import org.springframework.beans.factory.annotation.Value;
8+
import org.springframework.mail.SimpleMailMessage;
9+
import org.springframework.stereotype.Controller;
10+
import org.springframework.ui.Model;
11+
import org.springframework.validation.Errors;
12+
import org.springframework.web.bind.annotation.ModelAttribute;
13+
import org.springframework.web.bind.annotation.RequestMapping;
14+
import org.springframework.web.bind.annotation.RequestMethod;
15+
16+
import javax.servlet.http.HttpServletRequest;
17+
import javax.validation.Valid;
18+
import java.util.HashMap;
19+
import java.util.Iterator;
20+
import java.util.Map;
21+
import java.util.Set;
22+
23+
/**
24+
* Created by Olga on 7/20/2016.
25+
*/
26+
@Controller
27+
@RequestMapping("/mail")
28+
public class MailController {
29+
@Autowired
30+
public EmailServiceImpl emailService;
31+
32+
@Value("${attachment.invoice}")
33+
private String attachmentPath;
34+
35+
@Autowired
36+
@Qualifier("templateSimpleMessage")
37+
public SimpleMailMessage template;
38+
39+
private static final Map<String, Map<String, String>> labels;
40+
41+
static {
42+
labels = new HashMap<>();
43+
44+
//Simple email
45+
Map<String, String> props = new HashMap<>();
46+
props.put("headerText", "Send Simple Email");
47+
props.put("messageLabel", "Message");
48+
props.put("additionalInfo", "");
49+
labels.put("send", props);
50+
51+
//Email with template
52+
props = new HashMap<>();
53+
props.put("headerText", "Send Email Using Template");
54+
props.put("messageLabel", "Template Parameter");
55+
props.put("additionalInfo",
56+
"The parameter value will be added to the following message template:<br>" +
57+
"<b>This is the test email template for your email:<br>'Template Parameter'</b>"
58+
);
59+
labels.put("sendTemplate", props);
60+
61+
//Email with attachment
62+
props = new HashMap<>();
63+
props.put("headerText", "Send Email With Attachment");
64+
props.put("messageLabel", "Message");
65+
props.put("additionalInfo", "To make sure that you send an attachment with this email, change the value for the 'attachment.invoice' in the application.properties file to the path to the attachment.");
66+
labels.put("sendAttachment", props);
67+
}
68+
69+
@RequestMapping(value = {"/send", "/sendTemplate", "/sendAttachment"}, method = RequestMethod.GET)
70+
public String createMail(Model model,
71+
HttpServletRequest request) {
72+
String action = request.getRequestURL().substring(
73+
request.getRequestURL().lastIndexOf("/") + 1
74+
);
75+
Map<String, String> props = labels.get(action);
76+
Set<String> keys = props.keySet();
77+
Iterator<String> iterator = keys.iterator();
78+
while (iterator.hasNext()) {
79+
String key = iterator.next();
80+
model.addAttribute(key, props.get(key));
81+
}
82+
83+
model.addAttribute("mailObject", new MailObject());
84+
return "mail/send";
85+
}
86+
87+
@RequestMapping(value = "/send", method = RequestMethod.POST)
88+
public String createMail(Model model,
89+
@ModelAttribute("mailObject") @Valid MailObject mailObject,
90+
Errors errors) {
91+
if (errors.hasErrors()) {
92+
return "mail/send";
93+
}
94+
emailService.sendSimpleMessage(mailObject.getTo(),
95+
mailObject.getSubject(), mailObject.getText());
96+
97+
return "redirect:/home";
98+
}
99+
100+
@RequestMapping(value = "/sendTemplate", method = RequestMethod.POST)
101+
public String createMailWithTemplate(Model model,
102+
@ModelAttribute("mailObject") @Valid MailObject mailObject,
103+
Errors errors) {
104+
if (errors.hasErrors()) {
105+
return "mail/send";
106+
}
107+
emailService.sendSimpleMessageUsingTemplate(mailObject.getTo(),
108+
mailObject.getSubject(),
109+
template,
110+
mailObject.getText());
111+
112+
return "redirect:/home";
113+
}
114+
115+
@RequestMapping(value = "/sendAttachment", method = RequestMethod.POST)
116+
public String createMailWithAttachment(Model model,
117+
@ModelAttribute("mailObject") @Valid MailObject mailObject,
118+
Errors errors) {
119+
if (errors.hasErrors()) {
120+
return "mail/send";
121+
}
122+
emailService.sendMessageWithAttachment(
123+
mailObject.getTo(),
124+
mailObject.getSubject(),
125+
mailObject.getText(),
126+
attachmentPath
127+
);
128+
129+
return "redirect:/home";
130+
}
131+
}
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
package com.baeldung.spring.mail;
2+
3+
import org.springframework.mail.SimpleMailMessage;
4+
5+
/**
6+
* Created by Olga on 8/22/2016.
7+
*/
8+
public interface EmailService {
9+
void sendSimpleMessage(String to,
10+
String subject,
11+
String text);
12+
void sendSimpleMessageUsingTemplate(String to,
13+
String subject,
14+
SimpleMailMessage template,
15+
String ...templateArgs);
16+
void sendMessageWithAttachment(String to,
17+
String subject,
18+
String text,
19+
String pathToAttachment);
20+
}
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
package com.baeldung.spring.mail;
2+
3+
import org.springframework.beans.factory.annotation.Autowired;
4+
import org.springframework.core.io.FileSystemResource;
5+
import org.springframework.mail.MailException;
6+
import org.springframework.mail.SimpleMailMessage;
7+
import org.springframework.mail.javamail.JavaMailSender;
8+
import org.springframework.mail.javamail.MimeMessageHelper;
9+
import org.springframework.stereotype.Component;
10+
11+
import javax.mail.MessagingException;
12+
import javax.mail.internet.MimeMessage;
13+
import java.io.File;
14+
15+
/**
16+
* Created by Olga on 7/15/2016.
17+
*/
18+
@Component
19+
public class EmailServiceImpl implements EmailService {
20+
21+
@Autowired
22+
public JavaMailSender emailSender;
23+
24+
public void sendSimpleMessage(String to, String subject, String text) {
25+
try {
26+
SimpleMailMessage message = new SimpleMailMessage();
27+
message.setTo(to);
28+
message.setSubject(subject);
29+
message.setText(text);
30+
31+
emailSender.send(message);
32+
} catch (MailException exception) {
33+
exception.printStackTrace();
34+
}
35+
}
36+
37+
@Override
38+
public void sendSimpleMessageUsingTemplate(String to,
39+
String subject,
40+
SimpleMailMessage template,
41+
String ...templateArgs) {
42+
String text = String.format(template.getText(), templateArgs);
43+
sendSimpleMessage(to, subject, text);
44+
}
45+
46+
@Override
47+
public void sendMessageWithAttachment(String to,
48+
String subject,
49+
String text,
50+
String pathToAttachment) {
51+
try {
52+
MimeMessage message = emailSender.createMimeMessage();
53+
// pass 'true' to the constructor to create a multipart message
54+
MimeMessageHelper helper = new MimeMessageHelper(message, true);
55+
56+
helper.setTo(to);
57+
helper.setSubject(subject);
58+
helper.setText(text);
59+
60+
FileSystemResource file = new FileSystemResource(new File(pathToAttachment));
61+
helper.addAttachment("Invoice", file);
62+
63+
emailSender.send(message);
64+
} catch (MessagingException e) {
65+
e.printStackTrace();
66+
}
67+
}
68+
}

0 commit comments

Comments
 (0)