Simplified mail delivery using Spring's Java Mail Support (GO)

Source: Internet
Author: User

Reprinted from the use of Spring's Java mail support to simplify mail delivery

Nothing to do, look at "Spring in action", found that spring integrated support for Java Mail, a little excited to see it again, well, the words really simple a lot.

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 it yourself (for convenience, the following demo code is hardcoded into the code to save the hassle of configuration).

Spring provides mail delivery that not only supports the sending of simple messages, adds attachments, but also uses the Velocity template to control page styles (which should also support Freemarker).

First, add the jar package to the corresponding spring jar package and Java Mail.

We first have to declare a MailSender object because the MailSender object has only two overloaded send (...). Method, seems a little humble, we recommend the use of Javamailsender interface, or simply directly using the implementation class, Javamailsenderimpl. The author is the use of Javamailsenderimpl objects, rich features.

Declare the Javamailsenderimpl object and initialize it in the constructor (you can, of course, initialize with the IOC container):

 Public classSpringmailsender {//Spring's Mail tool class, implements the MailSender and Javamailsender interfaces    PrivateJavamailsenderimpl MailSender;  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 ("Asterisks"); ...

After getting the MailSender object, you can send the message, below is the sample code, not encapsulated, for reference only.

1. Send Simple Mail

/*** Simple Mail delivery **/ Public voidSimplesend () {//build a Simple mail object, see the nameSimplemailmessage SMM =NewSimplemailmessage (); //Set Message ParametersSmm.setfrom (Mailsender.getusername ()); Smm.setto ("[Email protected]"); Smm.setsubject ("Hello World"); Smm.settext ("Hello World via Spring Mail Sender"); //Send mailMailsender.send (SMM);}

2. Send mail with Attachments

/*** Email with attachments * *@throwsmessagingexception*/ Public voidAttachedsend ()throwsmessagingexception {//pay for more complex message formats and content using JavaMail's MimeMessageMimeMessage 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 attachmentClasspathresource file =NewClasspathresource ("Chrysanthemum.jpg"); //Add to AttachmentHelper.addattachment ("Attachment.jpg", file); //Send mailmailsender.send (msg);}

3. Send Rich Text mail

/**Send Rich Text messages *@throwsmessagingexception*/ Public voidRichcontentsend ()throwsmessagingexception {mimemessage msg=Mailsender.createmimemessage (); Mimemessagehelper Helper=NewMimemessagehelper (MSG,true);    Helper.setfrom (Mailsender.getusername ()); Helper.setto ("[Email protected]"); Helper.setsubject ("Rich content Mail"); //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>hello Html email</p></body>",            true); Filesystemresource file=NewFilesystemresource ("C:\\users\\public\\pictures\\sample pictures\\chrysanthemum.jpg"); Helper.addinline ("File", file); Mailsender.send (msg);}

4. Use velocity template to determine message style

Using the velocity template, you need the velocity of the jar package, can be downloaded on the official website, and add classpath, then need to declare a Velocityengine object, specific reference to the following code, this is the first time I use velocity, not very understanding, Many words have lost, hope forgive me.

Declares a Velocityengine object and initializes it in the constructor (IoC is optional)

...Privatevelocityengine Velocityengine; PublicSpringmailsender () {...//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 (); } }

Simple velocity template file (INDEX.VM):

<HTML><Head><styletype= "Text/css">h4{Color:Red;background:#efefef;}</style></Head><Body><h4>${user}</h4><P><P><I>${content}</I></Body></HTML>

Open up seems easy to understand, just plain HTML files, using some ${placeholder} as placeholders.

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

/** * Send mail using velocity template * * @throws messagingexception */public void Templatesend () throws Messagingexception {// 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", "mzule");    Model.put ("Content", "Hello"); Spring provides velocityengineutils to populate the template with data and convert it to a normal string object, String emailtext =    Velocityengineutils.mergetemplateintostring (Velocityengine, "INDEX.VM", model);    Work MimeMessage msg = Mailsender.createmimemessage () as in the above message    Mimemessagehelper helper = new Mimemessagehelper (msg, true);    Helper.setfrom (Mailsender.getusername ());    Helper.setto ("[email protected]");    Helper.setsubject ("Rich content mail");     Helper.settext (Emailtext, true); Mailsender.send (msg);}

Simplified mail delivery using Spring's Java Mail Support (GO)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.