I. Background knowledge
In the previous blog post: Using JavaMail to send mail and accept mail, we learned the native javaapi send mail, we will find that the code is much more, especially when the content of the message is very rich, we need to assemble HTML in Java, is not considered very troublesome.
Here we use a simpler approach: Spring + JavaMail + freemarker, with the Freemarker template engine, we no longer have to assemble HTML in Java.
Two. Environmental preparedness
Needless to say, the following we are prepared under the development environment:
1. Required JAR Package:
Spring.jar (2.5), Commons-logging.jar, Mail.jar, Freemarker.jar, Spring-webmvc.jar, Activation.jar
2. Install e-mail server, which we have mentioned in the previous blog post, and we will not repeat it here.
3. In d, put a picture "welcome.gif" and a Word file "Welcome to register. docx" to populate the message content.
Three. Code implementation
1. The code structure diagram is as follows:
2. Entity Bean:
/** * User Object */public class User {private string username;private string Password;public string GetUserName () {return Userna Me;} public void Setusername (String username) {this.username = username;} Public String GetPassword () {return password;} public void SetPassword (String password) {this.password = password;}}
2. Outgoing Mail Business interface
Public interface Emailservice {public void SendEmail (user user);
3. E-Mail Implementation
public class Emailserviceimpl implements Emailservice {private Javamailsender mailsender;private freemarkerconfigurer Freemarkerconfigurer; private static final String ENCODING = "Utf-8";p ublic void Setmailsender (Javamailsender mailsender) {this.mailsend ER = MailSender; }public void Setfreemarkerconfigurer (Freemarkerconfigurer freemarkerconfigurer) {this.freemarkerconfigurer = Freemarkerconfigurer;} /** * Send HTML formatted message with attachment */public void SendEmail (user user) {mimemessage msg = null;try {msg = Mailsender.createmimemessage (); Mimemessagehelper helper = new Mimemessagehelper (msg, True, ENCODING); Helper.setfrom ("[email protected]"); Helper.setto ("[email protected]"); Helper.setsubject (Mimeutility.encodetext ("estore Note successful message", ENCODING, "B") ); Helper.settext (Getmailtext (user), true); True indicates that the content of text is html//added to the embedded file, the 1th parameter is the CID identification of the file, the 2nd is the resource Helper.addinline ("Welcomepic", New File ("D:/welcome.gif")); Attachment Contents//Here the method call and insert picture are different, solve the Chinese problem of attachment name file File = new file ("d:/Welcome register. docx"); helper.adDattachment (Mimeutility.encodeword (File.getname ()), file);} catch (Exception e) {throw new RuntimeException ("Error Happens", e);} mailsender.send (msg); System.out.println ("Mail sent successfully ..."); /** * Constructs the message content through the template, the parameter contents will replace the ${content} tag in the template file.*/private String getmailtext (user user) throws Exception {//Gets the Freemarker template instance by specifying a template name. Freemarkerconfigurer.getconfiguration (). GetTemplate ("registe.html"); Freemarker transmits Dynamic Data map<string via map, string> map = new hashmap<string, string> (); Map.put ("username", user.getusername ()); Note that the Dynamic Data key matches the properties specified in the template tag map.put ("Password", User.getpassword ());//parse the template and replace the Dynamic data. Finally the content will replace the ${content} tag in the template file.
String HTMLText = freemarkertemplateutils.processtemplateintostring (template, map); return htmltext;}}
Solve the name garbled problem using: Mimeutility.encodetext (name, "UTF-8", "B")
Because of the specification of email, Chinese characters cannot be used in SMTP transmissions.
So you can use the Mimeutility method of the built-in class Encodetext to encode the recipient, sender name.
There are two ways of encoding: "B" stands for Base64, "Q" represents QP (quoted-printable) mode.
Attention:
1. The name and email address cannot be encoded together, such as a direct code "name" as the recipient will be an error.
2. The subject and content of mail do not require our explicit encoding. At set time these two items will be encoded by javax.mail themselves.
4. Spring Core Configuration
<?xml version= "1.0" encoding= "UTF-8"? ><beans xmlns= "Http://www.springframework.org/schema/beans" xmlns: Xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP" xmlns:tx= " Http://www.springframework.org/schema/tx "xsi:schemalocation=" Http://www.springframework.org/schema/beans http:/ /WWW.SPRINGFRAMEWORK.ORG/SCHEMA/BEANS/SPRING-BEANS-2.5.XSDHTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP/HTTP WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP/SPRING-AOP-2.5.XSDHTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/TX/HTTP Www.springframework.org/schema/tx/spring-tx-2.5.xsd "><bean id=" Freemarker "class=" Org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer "><property name=" Templateloaderpath " Value= "classpath:"/> <!--Specify template file Folder--><property name= "Freemarkersettings" ><!--settings Freemarker Environment Properties- -><props><prop key= "Template_update_delay" >1800</prop> <!--refresh the period of the template in seconds--><prop key = "Default_encoding" >utf-8</prop> <!--template encoding format--><prop key= "locale" >zh_CN</prop> <!--localization settings--></props> </property></bean><!--Note: The number of references here (such as username, password) is--><bean id= "MailSender" for the sender of the message class= "Org.springframework.mail.javamail.JavaMailSenderImpl" ><property name= "host" > <value>localhost </value> </property> <property name= "Javamailproperties" > <props> <prop key= "Mail.smtp.auth" >true</prop> <prop key= "Mail.smtp.timeout" >25 000</prop> </props> </property> <property name= "username" > <value>service</value> <!--sender Username--</property> <property name= "pa ssWOrd "> <value>123</value> <!--sender password--</property> </bean>& Lt;bean id= "Emailservice" class= "Com.zdp.sErvice.impl.EmailServiceImpl "><property name=" MailSender "ref=" MailSender "></property>< Property Name= "Freemarkerconfigurer" ref= "Freemarker" ></property></bean></beans>
5. template file:
<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >