JAVA Mail with Spring supports simplified mail sending

  • 2021-07-22 09:42:36
  • OfStack

When I have nothing to do, I read "Spring in Action" and found that Spring integrates support for JAVA Mail. I watched it once with a little excitement. Well, it's really much simpler.

The core of Spring mail sending is MailSender interface, and an implementation class JavaMailSenderImpl is provided in Spring 3.0, which is the core class of sending mail. It can be configured in a configuration file, or hard-coded into the code itself (for convenience, the following demo code is hard-coded into the code to save configuration trouble).

The mail delivery provided by Spring not only supports sending simple mail and adding attachments, but also controls page styles using velocity templates (freemarker should also be supported).

First, the corresponding Spring jar packets and Java Mail packets are added to the jar packets.

We must first declare an MailSender object, because the MailSender object has only two overloaded send (...) methods, which is somewhat rudimentary. We suggest using the JavaMailSender interface, or simply using the implementation class, JavaMailSenderImpl. The author is using JavaMailSenderImpl object, which is rich in functions.

Declare an JavaMailSenderImpl object and initialize it in the constructor (of course, you can also initialize it using the IoC container):


public class SpringMailSender
 {
 
 //
 Spring The mail tool class, which implements the MailSender And JavaMailSender Interface 
 private JavaMailSenderImpl
 mailSender;
  
 public SpringMailSender()
 {
 //
  Initialization JavaMailSenderImpl Of course, it is recommended in spring Configuration file, here for simplicity 
 mailSender
 = new JavaMailSenderImpl();
 //
  Setting parameters 
 mailSender.setHost("smtp.qq.com");
 mailSender.setUsername("mosaic@qq.com");
 mailSender.setPassword("asterisks");
 ...

After you get the MailSender object, you can send the mail. The following is the sample code, which is not encapsulated and is for reference only.

1. Send Simple Mail


/**
 *
  Simple mail sending 
 *
 */
public void simpleSend()
 {
 //
  Build a simple mail object, see the name and know the meaning 
 SimpleMailMessage
 smm = new SimpleMailMessage();
 //
  Setting Mail Parameters 
 smm.setFrom(mailSender.getUsername());
 smm.setTo("mosaic@126.com");
 smm.setSubject("Hello
 world");
 smm.setText("Hello
 world via spring mail sender");
 //
  Send Mail 
 mailSender.send(smm);
}

2. Send mail with attachments


/**
 *
  Mail sending with attachments 
 *
 *
 @throws MessagingException
 */
public void attachedSend()
throws MessagingException
 {
 // Use JavaMail Adj. MimeMessage Pay for more complex mail formats and content 
 MimeMessage
 msg = mailSender.createMimeMessage();
 // Create MimeMessageHelper Object that handles MimeMessage Auxiliary class of 
 MimeMessageHelper
 helper = new MimeMessageHelper(msg,
true);
 // Using helper classes MimeMessage Setting parameters 
 helper.setFrom(mailSender.getUsername());
 helper.setTo("mosaic@126.com");
 helper.setSubject("Hello
 Attachment");
 helper.setText("This
 is a mail with attachment");
 // Load file resources as attachments 
 ClassPathResource
 file = new ClassPathResource(
   "Chrysanthemum.jpg");
 // Accession of Annex 
 helper.addAttachment("attachment.jpg",
 file);
 // Send Mail 
 mailSender.send(msg);
}

3. Send rich text mail


/** Send rich text mail 
 *
 @throws MessagingException
 */
public void richContentSend()
throws MessagingException
 {
 MimeMessage
 msg = mailSender.createMimeMessage();
 
 MimeMessageHelper
 helper = new MimeMessageHelper(msg,
true);
 
 helper.setFrom(mailSender.getUsername());
 helper.setTo("mosaic@126.com");
 helper.setSubject("Rich
 content mail");
 // No. 1 2 Parameters true , denoting text The content of is html , and then notice <img/> Label, src='cid:file' , 'cid' Yes contentId The abbreviation of, 'file' Yes 1 Tags, which need to be called in the following code MimeMessageHelper Adj. addInline Method is replaced with a file 
 helper.setText(
   "<body><p>Hello
 Html Email</p><img src='cid:file'/></body>",
   true);
 
 FileSystemResource
 file = new FileSystemResource(
   "C:\\Users\\Public\\Pictures\\Sample
 Pictures\\Chrysanthemum.jpg");
 helper.addInline("file",
 file);
 
 mailSender.send(msg);
}

4. Use the Velocity template to determine the message style

Using Velocity template, jar package of Velocity is needed, which can be downloaded from the official website, and ClassPath is added, and then an VelocityEngine object needs to be declared. Specific reference to the following code, this is the first time the author uses Velocity, and I don't know much about it. I hope I forgive you.

Declare an VelocityEngine object and initialize it in the constructor (IoC is optional)


...
private VelocityEngine
 velocityEngine;
 
public SpringMailSender()
 {
  ...
 //
 Velocity Parameters of, pass the VelocityEngineFactoryBean Create VelocityEngine Which is also recommended for configuration in the configuration file 
 Properties
 props = System.getProperties();
 props.put("resource.loader",
"class");
 props
   .put("class.resource.loader.class",
     "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
 VelocityEngineFactoryBean
 v = new VelocityEngineFactoryBean();
 v.setVelocityProperties(props);
 try {
  velocityEngine
 = v.createVelocityEngine();
 }
catch (VelocityException
 e) {
  e.printStackTrace();
 }
catch (IOException
 e) {
  e.printStackTrace();
 }
 
}

Simple Velocity template file (index. vm):


<html>
<head>
<style type="text/css">
h4{
 color:red;
 background:#efefef;
}
</style>
</head>
<body>
<h4>${user}
 </h4>
<p><p>
<i>${content}</i>
</body>
</html>

It seems easy to open, except that the ordinary Html file uses 1 ${placeholder} as placeholders.

All Java does is load the template and insert the corresponding value into the placeholder.


/**
 *
  Use Velocity Template Send Mail 
 *
 *
 @throws MessagingException
 */
public
 void templateSend() throws MessagingException {
 //
  Declaration Map Object and fill in the key-value pair used to fill the template file 
 Map<String,
 String> model = new HashMap<String,
 String>();
 model.put("user",
 "MZULE");
 model.put("content",
 "Hello");
 //
 Spring Offered VelocityEngineUtils The template is filled with data and converted into a normal String Object 
 String
 emailText = VelocityEngineUtils.mergeTemplateIntoString(
   velocityEngine,
 "index.vm", model);
 //
  And above 1 The job of sending mail like this 
 MimeMessage
 msg = mailSender.createMimeMessage();
 MimeMessageHelper
 helper = new MimeMessageHelper(msg, true);
 helper.setFrom(mailSender.getUsername());
 helper.setTo("mosaic@126.com");
 helper.setSubject("Rich
 content mail");
 helper.setText(emailText,
 true);
 
 mailSender.send(msg);
}

Spring can be described as greatly simplifying the sending steps of mail. Although it may not be complicated for us to encapsulate ourselves, why do we need to rebuild the wheels when we have ready-made ones? (Of course, you can learn a lot from building wheels.)


Related articles: