1 Configure spring Send mail
The core of Spring email abstraction is the MailSender interface. As the name implies, the implementation of MailSender can be connected via email server to achieve the function of mail delivery, 19.1 shows.
Figure 19.1 Spring's MailSender interface is the core component of the spring email abstraction API. It sends the email to the mail server, which is delivered by the server.
Spring comes with a mailsender implementation that is Javamailsenderimpl, which uses the JavaMail API to send email. Spring app before sending an email, we have to assemble the Javamailsenderimpl as a bean in the spring application context.
1.1 Configuring the Mail transmitter
@Bean public MailSender mailSender(Environment env) { JavaMailSenderImpl mailSender = new JavaMailSenderImpl(); mailSender.setHost(env.getProperty("mailserver.host")); mailSender.setPort(Integer.parseInt(env.getProperty("mailserver.port"))); mailSender.setUsername(env.getProperty("mailserver.username")); mailSender.setPassword(env.getProperty("mailserver.password")); return mailSender; }
1.2 Assembling and using the mail transmitter
We want to send an email message to spitter users that his friend wrote a new spittle, so we need a way to send email, this method to accept the email address and spittle object information.
@Override public void sendSimpleSpittleEmail(String to, Spittle spittle) { SimpleMailMessage message = new SimpleMailMessage(); String spitterName = spittle.getSpitter().getFullName(); message.setFrom("[email protected]"); message.setTo(to); message.setSubject("New spittle from " + spitterName); message.setText(spitterName + " says: " + spittle.getText()); mailSender.send(message); }
2 Building rich-content email messages
Spring's email functionality is not limited to plain text email. We can add attachments and even use HTML to beautify the content of the message body. Let's start with the basics of adding attachments, and then go further and make our email messages more aesthetically pleasing with HTML.
2.1 Adding attachments
If you send an email with an attachment, the key trick is to create a multipart type of message--email consisting of multiple parts, one of which is the email, and the other part is the attachment.
Simplemailmessage is too simplistic for the need to send attachments. In order to send multipart type of email, you need to create a MIME (multipurpose Internet Mail Extensions) message, we can start with the Createmimemessage () method of the Mail sender:
MimeMessage message = mailSender.createMimeMessage();
The API of Javax.mail.internet.MimeMessage itself is somewhat cumbersome. The good news is that spring provides mimemessagehelper to help us. In order to use mimemessagehelper, we need to instantiate it and pass the MimeMessage to its constructor:
MimeMessageHelper helper = new MimeMessageHelper(message, true);
The second parameter of the constructor method, where it is a Boolean value of True, indicates that the message is of type multipart.
Once we get the Mimemessagehelper instance, we can assemble the email message. The main difference here is that the helper method is used to specify the details of the email instead of setting the Message object.
@Override public void sendSpittleEmailWithAttachment(String to, Spittle spittle) throws MessagingException { MimeMessage message = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true); String spitterName = spittle.getSpitter().getFullName(); helper.setFrom("[email protected]"); helper.setTo(to); helper.setSubject("New spittle from " + spitterName); helper.setText(spitterName + " says: " + spittle.getText()); ClassPathResource couponImage = new ClassPathResource("/collateral/coupon.png"); helper.addAttachment("Coupon.png", couponImage); mailSender.send(message); }
2.2 Sending Rich text content to email
Sending Rich Text email is not much different from sending a simple text email. The key is to set the text of the message to HTML. To do this, simply pass the HTML string to the helper's SetText () method and set the second argument to true:
The second parameter indicates that the first parameter passed in is HTML, so the content type of the message needs to be set accordingly.
Note that the passed in HTML contains a label for displaying the
logo of the spittr application in an email. The SRC attribute can be set to the standard "http:" URL to get Spittr's logo from the web. But here, we embed the logo image in the email. A value of "Cid:spitterlogo" indicates that a part of the message is a picture and is identified by Spitterlogo.
Adding an embedded picture to a message is similar to adding an attachment. But instead of using the helper AddAttachment () method This time, call the Addinline () method:
ClassPathResource couponImage = new ClassPathResource("coupon.png");helper.addInline("spitterLogo", couponImage);
The following is the new Sendrichspitteremail () method:
When creating the email body, using string concatenation to build HTML messages still makes me feel in the ointment. Before ending the email topic, let's look at how to use templates instead of string concatenation messages.
3 using templates to generate email
We need to express the email layout in a way that is close to the final HTML, then convert the template into a string and pass it to the helper's SetText () method. When converting a template to string, we have a variety of template options to choose from, including Apache Velocity and thymeleaf. Let's look at how to create rich text email messages using these two scenarios, starting with velocity.
3.1 Building an email message using velocity
In order to use velocity to lay out the email, we need to assemble the velocityengine into the Spitteremailserviceimpl. Spring provides a factory bean named Velocityenginefactorybean that makes it easy to generate velocityengine in the context of the spring application. Velocityenginefactorybean's statement is as follows:
Velocityenginefactorybean the only property to set is Velocityproperties. In this case, we configured it to load the velocity template from the classpath (see the velocity documentation for more details on configuring velocity).
Now we can assemble the velocity engine into the spitteremailserviceimpl. Since Spitteremailserviceimpl is automatically registered using component scanning, we can use @autowired to customize the assembly Velocityengine properties:
@AutowiredVelocityEngine velocityEngine;
Now that the Velocityengine property is available, we can use it to convert the velocity template to a string and send it as an email text. To help us do this, spring comes with velocityengineutils to simplify the task of merging velocity templates with model data into string. Here's how we might use it:
The only thing left in Java code is to get the merged email text and pass it to the helper's SetText () method:
helper.setText(emailText, true);
The template is located at the root of the classpath and is a file named EMAILTEMPLATE.VM, which may look like this:
3.2 Building an email message using thymeleaf
When we convert email templates to thymeleaf templates, Thymeleaf's WYSIWYG features are obvious:
Note that there are no custom tags (which you might see in the JSP). Although model properties are marked with "${}", they are used only in the value of the property and are not used outside as velocity. This template can be easily opened in a Web browser and presented in a complete form, without the need to rely on the processing of the Thymeleaf engine.
Using Thymeleaf to generate and send an email message is very similar to velocity:
The Thymeleaf engine here is the same as the springtemplateenginebean we used to build the Web view in the 6th chapter. Here, we inject it into the spitteremailserviceimpl using the constructor-injected method:
However, we need to make a little change to Springtemplateenginebean. In the 6th chapter, it is configured to parse the template from the context of the servlet, and our email template needs to be parsed from the classpath. So, in addition to servletcontexttemplateresolver, you need a classloadertemplateresolver:
Note that we set the prefix property to "mail/", which means it will start looking for the thymeleaf template under the "Mail" directory of the Classpath root. Therefore, the name of the email template file must be emailtemplate.html and located in the "Mail" directory at the root of the classpath.
Because we now have two template parsers, we need to use the Order property to indicate which one to use first. The Order property of Classloadertemplateresolver is 1, so let's modify servletcontexttemplateresolver and set its Order property to 2:
Now, the rest of the task is to modify the Springtemplateenginebean configuration so that it uses the two template parsers:
Until then, we had only one template parser, so we could inject it into the Templateresolver property of Springtemplateengine. But now that we have two template parsers, we have to use them as members of the set, and then inject this set into the Templateresolvers (complex) attribute.
Source
Https://github.com/myitroad/spring-in-action-4/tree/master/Chapter_19
List of attachments
- Classloadertr.jpg
- Emailtemplate.jpg
- Img19-1.jpg
- Richtext.jpg
- Sendrichspitteremail.jpg
- Templateeb.jpg
- Templatero.jpg
- Thymeleafengine.jpg
- Thymeleafsendemail.jpg
- Thymeleaftemplate.jpg
- Velocityefb.jpg
- Velocitytostr.jpg
19th-send email using spring