Skip to content

Commit 4ff269f

Browse files
committed
upgrade email article, move to spring-mvc-simple
1 parent e78ca7c commit 4ff269f

10 files changed

Lines changed: 426 additions & 2 deletions

File tree

‎spring-mvc-simple/README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,3 +5,4 @@
55
- [Spring 5 and Servlet 4 – The PushBuilder](http://www.baeldung.com/spring-5-push)
66
- [Servlet Redirect vs Forward](http://www.baeldung.com/servlet-redirect-forward)
77
- [Apache Tiles Integration with Spring MVC](http://www.baeldung.com/spring-mvc-apache-tiles)
8+
- [Guide to Spring Email](http://www.baeldung.com/spring-email)

‎spring-mvc-simple/pom.xml‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,15 @@
2020
<artifactId>spring-oxm</artifactId>
2121
<version>${spring-oxm.version}</version>
2222
</dependency>
23+
<dependency>
24+
<groupId>org.springframework</groupId>
25+
<artifactId>spring-context-support</artifactId>
26+
</dependency>
27+
<dependency>
28+
<groupId>com.sun.mail</groupId>
29+
<artifactId>javax.mail</artifactId>
30+
<version>1.6.1</version>
31+
</dependency>
2332
<dependency>
2433
<groupId>javax.servlet</groupId>
2534
<artifactId>javax.servlet-api</artifactId>
@@ -171,7 +180,7 @@
171180
<jstl.version>1.2</jstl.version>
172181
<javax.servlet.jsp-api.version>2.3.2-b02</javax.servlet.jsp-api.version>
173182
<javax.servlet-api.version>4.0.0</javax.servlet-api.version>
174-
<hibernate-validator.version>5.4.1.Final</hibernate-validator.version>
183+
<hibernate-validator.version>6.0.10.Final</hibernate-validator.version>
175184
<deploy-path>enter-location-of-server</deploy-path>
176185
<fileupload.version>1.3.2</fileupload.version>
177186
<java.version>1.8</java.version>

‎spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/ApplicationConfiguration.java‎

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,9 @@
88
import org.springframework.http.converter.HttpMessageConverter;
99
import org.springframework.http.converter.StringHttpMessageConverter;
1010
import org.springframework.http.converter.feed.RssChannelHttpMessageConverter;
11+
import org.springframework.mail.SimpleMailMessage;
12+
import org.springframework.mail.javamail.JavaMailSender;
13+
import org.springframework.mail.javamail.JavaMailSenderImpl;
1114
import org.springframework.web.accept.ContentNegotiationManager;
1215
import org.springframework.web.multipart.MultipartResolver;
1316
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
@@ -20,10 +23,11 @@
2023

2124
import java.util.ArrayList;
2225
import java.util.List;
26+
import java.util.Properties;
2327

2428
@Configuration
2529
@EnableWebMvc
26-
@ComponentScan(basePackages = { "com.baeldung.springmvcforms", "com.baeldung.spring.controller", "com.baeldung.spring.validator" })
30+
@ComponentScan(basePackages = { "com.baeldung.springmvcforms", "com.baeldung.spring.controller", "com.baeldung.spring.validator", "com.baeldung.spring.mail" })
2731
public class ApplicationConfiguration implements WebMvcConfigurer {
2832

2933
@Override
@@ -60,4 +64,29 @@ public void configureMessageConverters(List<HttpMessageConverter<?>> converters)
6064
converters.add(new RssChannelHttpMessageConverter());
6165
converters.add(new JsonChannelHttpMessageConverter());
6266
}
67+
68+
@Bean
69+
public SimpleMailMessage templateSimpleMessage() {
70+
SimpleMailMessage message = new SimpleMailMessage();
71+
message.setText("This is the test email template for your email:\n%s\n");
72+
return message;
73+
}
74+
75+
@Bean
76+
public JavaMailSender getJavaMailSender() {
77+
JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
78+
mailSender.setHost("smtp.gmail.com");
79+
mailSender.setPort(587);
80+
81+
mailSender.setUsername("my.gmail@gmail.com");
82+
mailSender.setPassword("password");
83+
84+
Properties props = mailSender.getJavaMailProperties();
85+
props.put("mail.transport.protocol", "smtp");
86+
props.put("mail.smtp.auth", "true");
87+
props.put("mail.smtp.starttls.enable", "true");
88+
props.put("mail.debug", "true");
89+
90+
return mailSender;
91+
}
6392
}
Lines changed: 132 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,132 @@
1+
package com.baeldung.spring.controller;
2+
3+
import com.baeldung.spring.mail.EmailServiceImpl;
4+
import com.baeldung.spring.domain.MailObject;
5+
import org.springframework.beans.factory.annotation.Autowired;
6+
import org.springframework.beans.factory.annotation.Value;
7+
import org.springframework.mail.SimpleMailMessage;
8+
import org.springframework.stereotype.Controller;
9+
import org.springframework.ui.Model;
10+
import org.springframework.validation.Errors;
11+
import org.springframework.web.bind.annotation.ModelAttribute;
12+
import org.springframework.web.bind.annotation.RequestMapping;
13+
import org.springframework.web.bind.annotation.RequestMethod;
14+
15+
import javax.servlet.http.HttpServletRequest;
16+
import javax.validation.Valid;
17+
import java.util.HashMap;
18+
import java.util.Iterator;
19+
import java.util.Map;
20+
import java.util.Set;
21+
22+
@Controller
23+
@RequestMapping("/mail")
24+
public class MailController {
25+
26+
@Autowired
27+
public EmailServiceImpl emailService;
28+
29+
@Value("${attachment.invoice}")
30+
private String attachmentPath;
31+
32+
@Autowired
33+
public SimpleMailMessage template;
34+
35+
private static final Map<String, Map<String, String>> labels;
36+
37+
static {
38+
labels = new HashMap<>();
39+
40+
//Simple email
41+
Map<String, String> props = new HashMap<>();
42+
props.put("headerText", "Send Simple Email");
43+
props.put("messageLabel", "Message");
44+
props.put("additionalInfo", "");
45+
labels.put("send", props);
46+
47+
//Email with template
48+
props = new HashMap<>();
49+
props.put("headerText", "Send Email Using Template");
50+
props.put("messageLabel", "Template Parameter");
51+
props.put("additionalInfo",
52+
"The parameter value will be added to the following message template:<br>" +
53+
"<b>This is the test email template for your email:<br>'Template Parameter'</b>"
54+
);
55+
labels.put("sendTemplate", props);
56+
57+
//Email with attachment
58+
props = new HashMap<>();
59+
props.put("headerText", "Send Email With Attachment");
60+
props.put("messageLabel", "Message");
61+
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.");
62+
labels.put("sendAttachment", props);
63+
}
64+
65+
@RequestMapping(method = RequestMethod.GET)
66+
public String showEmailsPage() {
67+
return "emails";
68+
}
69+
70+
@RequestMapping(value = {"/send", "/sendTemplate", "/sendAttachment"}, method = RequestMethod.GET)
71+
public String createMail(Model model,
72+
HttpServletRequest request) {
73+
String action = request.getRequestURL().substring(
74+
request.getRequestURL().lastIndexOf("/") + 1
75+
);
76+
Map<String, String> props = labels.get(action);
77+
Set<String> keys = props.keySet();
78+
Iterator<String> iterator = keys.iterator();
79+
while (iterator.hasNext()) {
80+
String key = iterator.next();
81+
model.addAttribute(key, props.get(key));
82+
}
83+
84+
model.addAttribute("mailObject", new MailObject());
85+
return "mail/send";
86+
}
87+
88+
@RequestMapping(value = "/send", method = RequestMethod.POST)
89+
public String createMail(Model model,
90+
@ModelAttribute("mailObject") @Valid MailObject mailObject,
91+
Errors errors) {
92+
if (errors.hasErrors()) {
93+
return "mail/send";
94+
}
95+
emailService.sendSimpleMessage(mailObject.getTo(),
96+
mailObject.getSubject(), mailObject.getText());
97+
98+
return "redirect:/home";
99+
}
100+
101+
@RequestMapping(value = "/sendTemplate", method = RequestMethod.POST)
102+
public String createMailWithTemplate(Model model,
103+
@ModelAttribute("mailObject") @Valid MailObject mailObject,
104+
Errors errors) {
105+
if (errors.hasErrors()) {
106+
return "mail/send";
107+
}
108+
emailService.sendSimpleMessageUsingTemplate(mailObject.getTo(),
109+
mailObject.getSubject(),
110+
template,
111+
mailObject.getText());
112+
113+
return "redirect:/home";
114+
}
115+
116+
@RequestMapping(value = "/sendAttachment", method = RequestMethod.POST)
117+
public String createMailWithAttachment(Model model,
118+
@ModelAttribute("mailObject") @Valid MailObject mailObject,
119+
Errors errors) {
120+
if (errors.hasErrors()) {
121+
return "mail/send";
122+
}
123+
emailService.sendMessageWithAttachment(
124+
mailObject.getTo(),
125+
mailObject.getSubject(),
126+
mailObject.getText(),
127+
attachmentPath
128+
);
129+
130+
return "redirect:/home";
131+
}
132+
}
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
package com.baeldung.spring.domain;
2+
3+
import javax.validation.constraints.Email;
4+
import javax.validation.constraints.NotNull;
5+
import javax.validation.constraints.Size;
6+
7+
/**
8+
* Created by Olga on 7/20/2016.
9+
*/
10+
public class MailObject {
11+
@Email
12+
@NotNull
13+
@Size(min = 1, message = "Please, set an email address to send the message to it")
14+
private String to;
15+
private String subject;
16+
private String text;
17+
18+
public String getTo() {
19+
return to;
20+
}
21+
22+
public void setTo(String to) {
23+
this.to = to;
24+
}
25+
26+
public String getSubject() {
27+
return subject;
28+
}
29+
30+
public void setSubject(String subject) {
31+
this.subject = subject;
32+
}
33+
34+
public String getText() {
35+
return text;
36+
}
37+
38+
public void setText(String text) {
39+
this.text = text;
40+
}
41+
}
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: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
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 java.io.File;
12+
13+
import javax.mail.MessagingException;
14+
import javax.mail.internet.MimeMessage;
15+
16+
/**
17+
* Created by Olga on 7/15/2016.
18+
*/
19+
@Component
20+
public class EmailServiceImpl implements EmailService {
21+
22+
@Autowired
23+
public JavaMailSender emailSender;
24+
25+
public void sendSimpleMessage(String to, String subject, String text) {
26+
try {
27+
SimpleMailMessage message = new SimpleMailMessage();
28+
message.setTo(to);
29+
message.setSubject(subject);
30+
message.setText(text);
31+
32+
emailSender.send(message);
33+
} catch (MailException exception) {
34+
exception.printStackTrace();
35+
}
36+
}
37+
38+
@Override
39+
public void sendSimpleMessageUsingTemplate(String to,
40+
String subject,
41+
SimpleMailMessage template,
42+
String ...templateArgs) {
43+
String text = String.format(template.getText(), templateArgs);
44+
sendSimpleMessage(to, subject, text);
45+
}
46+
47+
@Override
48+
public void sendMessageWithAttachment(String to,
49+
String subject,
50+
String text,
51+
String pathToAttachment) {
52+
try {
53+
MimeMessage message = emailSender.createMimeMessage();
54+
// pass 'true' to the constructor to create a multipart message
55+
MimeMessageHelper helper = new MimeMessageHelper(message, true);
56+
57+
helper.setTo(to);
58+
helper.setSubject(subject);
59+
helper.setText(text);
60+
61+
FileSystemResource file = new FileSystemResource(new File(pathToAttachment));
62+
helper.addAttachment("Invoice", file);
63+
64+
emailSender.send(message);
65+
} catch (MessagingException e) {
66+
e.printStackTrace();
67+
}
68+
}
69+
}
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
#this property file will have to be loaded explicitly as this is not a Spring Boot project
2+
3+
# Gmail SMTP
4+
spring.mail.host=smtp.gmail.com
5+
spring.mail.port=587
6+
spring.mail.username=username
7+
spring.mail.password=password
8+
spring.mail.properties.mail.smtp.auth=true
9+
spring.mail.properties.mail.smtp.starttls.enable=true
10+
11+
# Amazon SES SMTP
12+
#spring.mail.host=email-smtp.us-west-2.amazonaws.com
13+
#spring.mail.username=username
14+
#spring.mail.password=password
15+
#spring.mail.properties.mail.transport.protocol=smtp
16+
#spring.mail.properties.mail.smtp.port=25
17+
#spring.mail.properties.mail.smtp.auth=true
18+
#spring.mail.properties.mail.smtp.starttls.enable=true
19+
#spring.mail.properties.mail.smtp.starttls.required=true
20+
21+
# path to attachment file
22+
attachment.invoice=path_to_file

0 commit comments

Comments
 (0)