Java uses spring Javamailsenderimpl to send messages that support plain text, attachments, HTML, velocity templates
Blog Category:
This article mainly introduces the use of Javamailsenderimpl to send mail. The general message is sent first, followed by the sending of rich Text (HTML) messages and the use of velocity as a template for sending messages.
Message delivery is divided into three steps: creating a Mail sender , writing a message, and sending a message .
Spring's Javamailsenderimpl provides powerful mail-sending capabilities for sending plain text messages, email with attachments, HTML-formatted messages, email with pictures, setting the Send content encoding format, and setting the sender's display name.
As described below, many of the sample code are hard-coded strings, and it is recommended that you use spring's configuration file for the actual use.
1. Create a mail transmitter
First define the Javamailsenderimpl object, and the SMTP related information settings, the equivalent of our own mailbox, as follows:
Java code
- Javamailsenderimpl MailSender = new Javamailsenderimpl ();
- Mailsender.sethost ("smtp.qq.com");
- Mailsender.setusername ("[email protected]");
- Mailsender.setpassword ("asterisks");
Javamailsenderimpl MailSender = new Javamailsenderimpl () mailsender.sethost ("smtp.qq.com"); Mailsender.setusername ( "[Email protected]"); Mailsender.setpassword ("asterisks");
Of course, the better way is to use the configuration file configuration, here is just introduction, ignoring hard coding first.
The above host is the mailbox service SMTP address, user name, password for the user's own mailbox. In addition to the above, you can also set
Setport (int port), Setprotocol (String protocol), etc., can be temporarily not considered.
So we've created a mail sender like this.
2, start to write mail, write the contents of the message
Javamailsenderimpl SupportMimeMessages和
SimpleMailMessages。
MimeMessages为复杂邮件模板,支持文本、附件、html、图片等。
Simplemailmessages implements the Mimemessagehelper, which supports text for regular mail templates.
Let's take simplemailmessages as an example to introduce
Java code
- Simplemailmessage SMM = new Simplemailmessage ();
- Set Message parameters
- Smm.setfrom (Mailsender.getusername ());
- Smm.setto ("[email protected]");
- Smm.setsubject ("Hello World");
- Smm.settext ("Hello World via Spring Mail Sender");
- Send mail
- Mailsender.send (SMM);
Simplemailmessage SMM = new Simplemailmessage ();//Set Mail parameters Smm.setfrom (mailsender.getusername ()); Smm.setto ("[Email Protected], smm.setsubject ("Hello World"), Smm.settext ("Hello World via Spring Mail Sender");//Send mail Mailsender.send ( SMM);
In this way, we have completed the writing of a Simple mail, for complex mail, writing and sending the following
Java code
- Pay for more complex message formats and content using JavaMail's MimeMessage
- MimeMessage msg = Mailsender.createmimemessage ();
- Create a Mimemessagehelper object to handle MimeMessage helper classes
- Mimemessagehelper helper = new Mimemessagehelper (msg, true);
- Setting parameters with auxiliary class MimeMessage
- Helper.setfrom (Mailsender.getusername ());
- Helper.setto ("[email protected]");
- Helper.setsubject ("Hello Attachment");
- Helper.settext ("This was a mail with attachment");
- Load the file resource as an attachment
- Classpathresource file = new Classpathresource ("chrysanthemum.jpg");
- Add to Attachment
- Helper.addattachment ("attachment.jpg", file);
- Send mail
- Mailsender.send (SMM);
Use JavaMail's mimemessage to pay for more complex message formats and content mimemessage msg = Mailsender.createmimemessage ();//Create Mimemessagehelper objects, Helper classes that handle mimemessage mimemessagehelper helpers = new Mimemessagehelper (msg, true);//Use auxiliary class MimeMessage to set parameters Helper.setfrom ( Mailsender.getusername ()); Helper.setto ("[email protected]"); Helper.setsubject ("Hello Attachment"); Helper.settext ("This was a mail with Attachment");//Load file resource as Attachment Classpathresource file = new Classpathresource ("chrysanthemum.jpg");// Add Attachment helper.addattachment ("attachment.jpg", file);//Send mail Mailsender.send (SMM);
Where Mimemessagehelper is the auxiliary class mimemessages. The above contains a resource file as an attachment for sending. For normal file sending methods are as follows:
Java code
- Filesystemresource file = new Filesystemresource ("c:\\users\\image1.jpg");
- Helper.addinline ("file", file);
Filesystemresource file = new Filesystemresource ("c:\\users\\image1.jpg"); Helper.addinline ("File", file);
3. Send mail
2 already contains the sent code, just use the Javamailsenderimpl send interface. Support Type is
Java code
- void Send (MimeMessage mimemessage)
- Send the given JavaMail MIME message.
- void Send (mimemessage[] mimemessages)
- Send the given array of JavaMail MIME messages in batch.
- void Send (Mimemessagepreparator mimemessagepreparator)
- Send the JavaMail MIME message prepared by the given Mimemessagepreparator.
- void Send (mimemessagepreparator[] mimemessagepreparators)
- Send the JavaMail MIME messages prepared by the given mimemessagepreparators.
- void Send (Simplemailmessage simplemessage)
- Send the given Simple mail message.
- void Send (simplemailmessage[] simplemessages)
- Send the given array of Simple mail messages in batch.
Voidsend (mimemessage mimemessage) Send The given JavaMail MIME message. Voidsend (mimemessage[] mimemessages) Send the given array of JavaMail MIME messages in batch. Voidsend (mimemessagepreparator mimemessagepreparator) Send the JavaMail MIME message prepared by the given Mimemessagepreparator. Voidsend (mimemessagepreparator[] mimemessagepreparators) Send the JavaMail MIME messages prepared by the given Mimemessagepreparators. Voidsend (simplemailmessage simplemessage) Send The given Simple mail message. Voidsend (simplemailmessage[] Simplemessages) Send The given array of Simple mail messages in batch.
Here's how to send a rich text file and send a message using velocity as a template.
4. Send HTML file
It is only necessary to set the HTML to True when Mimemessagehelper settext. SetText introduced as follows:
XML code
- SetText (String text, Boolean html)
- Set the given text directly as content in Non-multipart mode or as default body part in multipart mode.
SetText (String text, boolean html) Set the given text directly as content in Non-multipart mode or as default body par T in multipart mode.
The sample code (including attachments) is as follows:
Java code
- //the second parameter true, indicating that the contents of text are HTML
- //note tag, src= ' Cid:file ', ' CID ' is the abbreviation for ContentID, ' file ' is a marker, You need to call Mimemessagehelper's Addinline method in a later code to replace the file
- helper.settext (true);
- filesystemresource file = new Filesystemresource ( "c:\\users\\image1.jpg");
- Helper.addinline (
The second parameter, True, indicates that the content of text is html//note tag, src= ' Cid:file ', ' CID ' is the abbreviation for ContentID, ' file ' is a token, You need to call Mimemessagehelper's Addinline method in a later code to replace the file Helper.settext ("<body><p>hello Html email</p>< IMG src= ' cid:file '/></body> ", true); Filesystemresource file = new Filesystemresource ("c:\\users\\image1.jpg"); Helper.addinline ("File", file);
5. Send a message using velocity as a template
Using the velocity template, you need the velocity jar package, which can be downloaded on the official website and added to Classpath.
The principle of sending a message using velocity as a template is as follows:
A similar to web programming, the velocity as the front end, in Java to set the value of the variables to be displayed in the VM
B convert VM content to text using Velocityengineutils's mergetemplateintostring function
C Send a message as you send an HTML message with 4
So the most important process will be to convert the contents of the VM to a string, that is, to set the message content, the other is not different from the above
5.1 Create a new VM file named INDEX.VM
Java code
-
-
-
- <body>
- <div>${user} </div>
- <div>${content}</div>
- </body>
- "Background-color: #ffffff; White-space:normal "> </SPAN>
The HTML header definition is omitted for convenience.
Where ${user} is the velocity syntax, the equivalent of a variable, in a Java program can set the value of this variable in the front-end display.
5.2 Creating a Velocityenginefactorybean object and setting properties
Java code
- The parameters of velocity, created velocityengine through Velocityenginefactorybean, are also recommended in the configuration file
- Properties Properties = System.getproperties ();
- Properties.put ("Resource.loader", "class");
- Properties.put ("Class.resource.loader.class", " Org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader ");
- Velocityenginefactorybean v = new Velocityenginefactorybean ();
- V.setvelocityproperties (properties);
The velocity parameter, created by Velocityenginefactorybean Velocityengine, is also recommended in the configuration file for the properties properties System.getproperties ();p roperties.put ("Resource.loader", "class");p roperties.put ("Class.resource.loader.class", "Org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); Velocityenginefactorybean v = new Velocityenginefactorybean (); V.setvelocityproperties (properties);
5.3 Convert VM content to normal string
Java code
- // declares the Map object and fills in the key-value pairs used to populate the template file
- map< String, string> model = new hashmap<string, string > ();
- model.put (
- model.put (
- // spring provides the velocityengineutils to populate the template with data and converted to a normal String object
- string emailtext = Velocityengineutils.mergetemplateintostring (Velocityengine, "INDEX.VM", model);
Declare the Map object and fill in the key values used to populate the template file with the map<string, string> model = new hashmap<string, string> (); Model.put ("User", "ooo Model.put ("Content", "Nihao");//spring provides the velocityengineutils to populate the template with data and convert it to a normal string object string Emailtext = Velocityengineutils.mergetemplateintostring (Velocityengine, "INDEX.VM", model);
This allows us to populate the variable values in the VM and convert the content to string
5.4 Set message content, same as 4
Java code
- Helper.settext (Emailtext, true);
Helper.settext (Emailtext, true);
Other content is the same as the above 1, 2, 3 process.
Note: The VM file format needs to be consistent with the message encoding or it will appear garbled
Java uses spring Javamailsenderimpl to send messages that support plain text, attachments, HTML, velocity templates