1, Javamailsenderimpl class
The core of spring's message delivery is the MailSender interface, which provides an implementation class Javamailsenderimpl in Spring3.0, which is the core class for sending messages.
You can do this by configuring it in a configuration file, or by hard coding yourself into code.
2. Preparatory work
Build the spring environment, where the default learner has been successfully built.
Download the JavaMail jar package and import the project.
Http://www.oracle.com/technetwork/java/javamail/index-138643.html
3. Case code
Importjava.io.IOException;ImportJava.util.HashMap;ImportJava.util.Map;Importjava.util.Properties;Importjavax.mail.MessagingException;ImportJavax.mail.internet.MimeMessage;ImportOrg.apache.velocity.app.VelocityEngine;Importorg.apache.velocity.exception.VelocityException;ImportOrg.springframework.core.io.ClassPathResource;ImportOrg.springframework.core.io.FileSystemResource;ImportOrg.springframework.mail.SimpleMailMessage;ImportOrg.springframework.mail.javamail.JavaMailSenderImpl;ImportOrg.springframework.mail.javamail.MimeMessageHelper;ImportOrg.springframework.ui.velocity.VelocityEngineFactoryBean;Importorg.springframework.ui.velocity.VelocityEngineUtils; Public classSpringmailsender {//Spring's Mail tool class, implements the MailSender and Javamailsender interfaces PrivateJavamailsenderimpl MailSender; //using the velocity template, you need a jar package for velocity, and then you need to declare a Velocityengine object PrivateVelocityengine Velocityengine; /*** Create a mail transmitter*/ PublicSpringmailsender () {//initialization of the Javamailsenderimpl, of course, is recommended in the spring configuration file, here for simpleMailSender =NewJavamailsenderimpl (); //Setting ParametersMailsender.sethost ("smtp.qq.com"); Mailsender.setusername ("[Email protected]"); Mailsender.setpassword ("555555"); //after declaring a Velocityengine object, you need to initialize it in the constructor (IoC is optional)//The parameters of velocity, created velocityengine through Velocityenginefactorybean, are also recommended in the configuration fileProperties props =system.getproperties (); Props.put ("Resource.loader", "Class"); Props.put ("Class.resource.loader.class", "Org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); Velocityenginefactorybean v=NewVelocityenginefactorybean (); V.setvelocityproperties (props); Try{velocityengine=V.createvelocityengine (); } Catch(velocityexception e) {e.printstacktrace (); } Catch(IOException e) {e.printstacktrace (); } } /*** Method Name: Simplesend * Method Effect: TODO Simple Mail Send * Creator: Jxufe Hehaiyang * Created: 2015-2-7 pm 06:47:30 * @param @throwsException * return value type: void *@throws */ Public voidSimplesend ()throwsException {//building a Simple Mail object//Simplemailmessages implements the Mimemessagehelper, which supports text for regular mail templates. Simplemailmessage SMM =NewSimplemailmessage (); //Set Message ParametersSmm.setfrom (Mailsender.getusername ()); Smm.setto ("[Email protected]"); Smm.setsubject ("Hello World"); Smm.settext ("Nice"); //Send mailMailsender.send (SMM); } /*** Method Name: Attachedsend * Method function: TODO with attachment mail send * Creator: Jxufe Hehaiyang * Created: 2015-2-7 06:47:22 * @param @throwsmessagingexception * return value type: void *@throws */ Public voidAttachedsend ()throwsmessagingexception {//pay for more complex message formats and content using JavaMail's MimeMessage//Mimemessages is a complex mail template that supports text, attachments, HTML, images, and more. MimeMessage msg =Mailsender.createmimemessage (); //Create a Mimemessagehelper object to handle MimeMessage helper classesMimemessagehelper helper =NewMimemessagehelper (MSG,true); //setting parameters with auxiliary class MimeMessageHelper.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//file address corresponds to SRC directoryClasspathresource file =NewClasspathresource ("Ehcache.xsd"); //Add to AttachmentHelper.addattachment ("Ehcache.xsd", file); //Send mailmailsender.send (msg); } /*** Method Name: Richcontentsend * Method effect: TODO send Rich Text message * Creator: Jxufe Hehaiyang * created: 2015-2-7 06:47:14 * @param @throwsmessagingexception * return value type: void *@throws */ Public voidRichcontentsend ()throwsmessagingexception {mimemessage msg=Mailsender.createmimemessage (); Mimemessagehelper Helper=NewMimemessagehelper (MSG,true); Helper.setfrom (Mailsender.getusername ()); Helper.setto ("[Email protected]"); Helper.setsubject ("Message title"); //The second parameter, True, indicates that the content of text is HTML, and then note that the 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 fileHelper.settext ("<body><p style= ' color:red; ' >hello Html email</p></body> ", true); //file address corresponds to SRC directoryClasspathresource file =NewClasspathresource ("Logo.png"); //file address corresponding to system directory//filesystemresource file = new Filesystemresource ("C:\\users\\hiyoung\\desktop\\logo.png");Helper.addinline ("File", file); Mailsender.send (msg); } /*** Method Name: Templatesend * Method effect: TODO use velocity template to send mail * Creator: Jxufe Hehaiyang * Created: 2015-2-7 pm 06:47:0 5 *@param @throwsmessagingexception * return value type: void *@throws */ Public voidTemplatesend ()throwsmessagingexception {//declares the Map object and fills in the key-value pairs used to populate the template filemap<string, object> model =NewHashmap<string, object>(); Model.put ("User", "Hehaiyang"); Model.put ("Content", "Good evening!"); //Spring provides velocityengineutils to populate the template with data and convert it to a normal string object//file address corresponds to SRC directoryString Emailtext =velocityengineutils.mergetemplateintostring (Velocityengine,"/VELOCITY/MAIL.VM", model); //work with the same email as aboveMimeMessage msg =Mailsender.createmimemessage (); Mimemessagehelper Helper=NewMimemessagehelper (MSG,true); Helper.setfrom (Mailsender.getusername ()); Helper.setto ("[Email protected]"); Helper.setsubject ("Rich content Mail"); Helper.settext (Emailtext,true); Mailsender.send (msg); } }
Velocity Template mail.vm
<HTML><Head><styletype= "Text/css">h4{Color:Red;background:#efefef;}</style></Head><Body> <h4>${user}</h4> <P><P> <I>${content}</I></Body></HTML>
4. Problems that may be encountered
Exception 1:
Workaround:
If you encounter the exception shown, please check your configured send mailbox, there is no open pop3/smtp service.
Exception 2:
Exception in thread "main" java.lang.noclassdeffounderror:com/sun/mail/util/Lineinputstream at Javax.mail.Session.loadProvidersFromStream (Session.java:928) at javax.mail.session.access$000 (session.java:174) at javax.mail.session$1.load (session.java:870) at Javax.mail.Session.loadResource (Session.java:1084) at javax.mail.Session.loadProviders ( Session.java:889) at javax.mail.Session. <init> (session.java:210) at javax.mail.Session.getInstance (session.java:249)
Workaround:
If you are using a JDK1.5 or above environment, you should encounter the exception shown because the Javaee.jar package in the environment conflicts with the Java Mail package.
Find the Javaee.jar package to remove the mail package and mail subordinate packages, remove the conflict.
5. Testing
Change the method that Springmailsender calls, and test send messages individually.
Public class sendertest { publicstaticvoid main (string[] args) { try { springmailsender m=new springmailsender (); M.richcontentsend (); System.out.println ("sent successfully!") ); Catch (Exception e) { System.out.println (e.tostring ()); }}}
Send mail using Javamailsenderimpl class under Spring3.0