Spring is very good for sending mail support, we just have to configure the Mail sender, write good mail to send the method of the specific operation, then the implementation is not very difficult, but this process often there will be such or such a mistake, So after finishing this article, I will summarize the error and solution of Spring Mail sending easily.
About the mail sent, there are only a few cases, one is plain text sent, one is the HTML form of the send, one is sent with an attachment, one is to send a mass of things to take, for these several I will hit, my code in the first part of a large class, the following three kinds of classes into a generation, So there will be two types of configuration files
The first large class of mail sent "plain text send"
Must pack: Spring.jar,common-logging.jar,mail.jar,servlet.jar,common-collection.jar
First we look at spring configuration file Applicationcontext.xml
<?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 "> <!--define the mail sender, configure the sender details--><bean id=" MailSender " class= "Org.springframework.mail.javamail.JavaMailSenderImpl" ><property name= "host" value= "smtp.163.com"/ ><property name= "Port" value= "/><property name=" username "value=" Emailusername "/><property Name= "Password" value= "Emailpassword"/><property name= "defaultencoding" value= "Utf-8"/><property name= "JAvamailproperties "><props><prop key=" Mail.smtp.auth ">true</prop></props></ Property></bean><bean id= "Emailservice" class= " Com.javacrazyer.comon.SendOrderConfirmationEmailAdvice "><property name=" MailSender "ref=" MailSender "/> </bean></beans>
The entity class used Order.java
Package Com.javacrazyer.comon;import Java.io.serializable;public class Order implements Serializable {/* Private fields */private int orderid;private string username;private string useremail;public int Getorderid () {return orderId;} public void Setorderid (int orderId) {this.orderid = orderId;} Public String GetUserName () {return username;} public void Setusername (String username) {this.username = username;} Public String getUserEmail () {return useremail;} public void Setuseremail (String useremail) {this.useremail = UserEmail;}}
The interface class of the Mail sending class Mailservice.java
Package com.javacrazyer.comon;/** * Send mail using spring * */public interface Mailservice {void Sendordermail (order order);}
Specifically implemented mail-sending class Sendorderconfirmationemailadvice.java
Package Com.javacrazyer.comon;import Java.io.bufferedreader;import Java.io.ioexception;import Java.io.inputstreamreader;import Org.springframework.mail.mailsender;import Org.springframework.mail.simplemailmessage;public class Sendorderconfirmationemailadvice implements MailService{ Private String from= "[email protected]"; Sender e-mail address, must be the same as the mailbox address in the spring configuration file private String registetemplatename = "Com/javacrazyer/comon/mail_registe.txt"; Private MailSender mailsender;public void Setmailsender (MailSender mailsender) {this.mailsender = MailSender; }public void Sendordermail (order order) {//simplemialmessage can only be used to send messages in text format simplemailmessage mail = new Simplemailmessage (); Mail.setfrom (This.from); Mail.setto (Order.getuseremail ()); Mail.setsubject (" Congratulations on your successful registration as a member of Someday Mall! "); Mail.settext (Loadtemplatecontent (registetemplatename) ReplaceAll ("\\$\\{loginname\\}", Order.getUsername ())); This.mailSender.send (mail);} private string Loadtemplatecontent (string templatename) {StringBuilder sb = new STRIngbuilder (); BufferedReader br= null;try{br = new BufferedReader (New InputStreamReader (Thread.CurrentThread (). Getcontextclassloader (). getResourceAsStream (templatename), "UTF-8")); String lineseparator = System.getproperty ("Line.separator"); for (string str = null; (str = br.readline ()) = null;) {sb.append (str); Sb.append (LineSeparator);}} catch (IOException e) {e.printstacktrace ();} Finally{if (BR! = null) {try {br.close ();} catch (IOException e) {e.printstacktrace ()}}} return sb.tostring ();}}
Use of the Mail_registe.txt
Dear ${loginname}: Hello! Congratulations on becoming a member of someday Mall! Your login user name is: ${loginname} your Login password is: ****** (hide) Site URL:/http www.yoursitename.cn Contact Email: [Email protected]
Test send
Package Com.javacrazyer.service.test;import Org.junit.test;import Org.springframework.context.ApplicationContext; Import Org.springframework.context.support.classpathxmlapplicationcontext;import Com.javacrazyer.comon.mailservice;import Com.javacrazyer.comon.order;public class Userservicetest {@Testpublic void Test () throws Interruptedexception {ApplicationContext context = new Classpathxmlapplicationcontext (" Applicationcontext.xml "); Mailservice SF = (mailservice) context.getbean ("Emailservice"); Order order = New Order (); Order.setusername ("Cheneywu") ; Order.setuseremail ("[email protected]"); Sf.sendordermail (order);}}
Pay attention to the information in the mailbox.
The second class of mail sent "HTML format send, Mass, attachment"
In addition to the bread, but also need to spring-webmvc.jar,freemarker.jar, why need to Freemarker, because to send HTML file, so first write the HTML content of the file, Then use the template Freemarker to match the values, and spring has a good support for Freemarker.
Spring configuration file Applicatoncontext-html.xml
<?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:mailtemplate"/><!--Specify template file directory--><property name= "freemarkersettings" ><!-- Set Freemarker Environment Properties--><props><prop key= "Template_update_delay" >1800</prop><!--Refresh the period of the template, Units are seconds--><prop key= "default_encoding" >utf-8</prop>< encoding format for!--templates--><prop key= locale >zh_CN</prop><!--localization settings--></props ></property></bean><!--Note: The parameters here (such as user name, password) are--><bean id= "MailSender" class= "for the sender of the message. Org.springframework.mail.javamail.JavaMailSenderImpl "><property name=" host "value=" smtp.163.com "/>< Property name= "Port" value= "/><property name=" username "value=" emailusername "/><property name=" Password "value=" Emailpassword "/><property name=" defaultencoding "value=" Utf-8 "/><property name=" Javamailproperties "><props><prop key=" Mail.smtp.auth ">true</prop></props></ Property></bean><bean id= "Emailservice" class= "Com.javacrazyer.comon.EmailService" ><property Name= "MailSender" ref= "MailSender" ></property><property name= "Freemarkerconfigurer" ref= "FreeMarker" ></property></bean></beans>
Template file under the mailtemplate template file Registe.ftl "This file No name, suffix does not matter, as long as the content is HTML content."