Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Spring to make Java Mail support to simplify email sending

2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

In this issue, the editor will bring you about how to use Spring to make Java Mail support to simplify email sending. The article is rich in content and analyzed and described from a professional point of view. I hope you can get something after reading this article.

The core of Spring's mail delivery is the MailSender interface, which provides an implementation class JavaMailSenderImpl in Spring3.0, which is the core class for sending mail. You can use it by configuring it in the configuration file, or you can hard-code it into the code yourself (for convenience, the following demonstration code is hard-coded into the code, saving configuration hassle).

The mail delivery provided by Spring not only supports the sending of simple messages and the addition of attachments, but also allows you to use velocity templates to control page styles (freemarker should also be supported).

First of all, add the corresponding Spring jar package and Java Mail jar package.

We first have to declare a MailSender object, because the MailSender object has only two overloaded send (...). Method, which is a bit crude, we suggest choosing the JavaMailSender interface, or simply using the implementation class, JavaMailSenderImpl. The author uses JavaMailSenderImpl objects with rich functions.

Declare the JavaMailSenderImpl object and initialize it in the constructor (or you can initialize it using the IoC container):

The mail utility class of public class SpringMailSender {/ / Spring implements the MailSender and JavaMailSender interfaces private JavaMailSenderImpl mailSender; public SpringMailSender () {/ / initialize JavaMailSenderImpl. Of course, it is recommended to configure it in the spring configuration file. Here, it is for simple mailSender = new JavaMailSenderImpl (); / / to set the parameters mailSender.setHost ("smtp.qq.com"); mailSender.setUsername ("786553789@qq.com"); mailSender.setPassword ("556WULI779");...

Once you have the MailSender object, you can send an e-mail. Here is the sample code, without encapsulation, for reference only.

1. Send a simple email

/ * simple email delivery * * / public void simpleSend () {/ / build a simple email object, see SimpleMailMessage smm = new SimpleMailMessage (); / / set email parameters smm.setFrom (mailSender.getUsername ()); smm.setTo ("mosaic@126.com"); smm.setSubject ("Hello world"); smm.setText ("Hello world via spring mail sender"); / / send email mailSender.send (smm);}

2. Send mail with attachments

/ * send mail with attachments * * @ throws MessagingException * / public void attachedSend () throws MessagingException {/ / use JavaMail's MimeMessage to pay for more complex email format and content MimeMessage msg = mailSender.createMimeMessage (); / / create MimeMessageHelper object to handle MimeMessage's helper class MimeMessageHelper helper = new MimeMessageHelper (msg, true); / / use helper class MimeMessage to set the parameter helper.setFrom (mailSender.getUsername ()) Helper.setTo ("mosaic@126.com"); helper.setSubject ("Hello Attachment"); helper.setText ("This is a mail with attachment"); / / load file resources as attachments ClassPathResource file = new ClassPathResource ("Chrysanthemum.jpg"); / / add attachment helper.addAttachment ("attachment.jpg", file); / / send email mailSender.send (msg);}

3. Send rich text email

/ * * send rich text email * @ throws MessagingException * / public void richContentSend () throws MessagingException {MimeMessage msg = mailSender.createMimeMessage (); MimeMessageHelper helper = new MimeMessageHelper (msg, true); helper.setFrom (mailSender.getUsername ()); helper.setTo ("mosaic@126.com"); helper.setSubject ("Rich content mail"); / / the second parameter true indicates that the content of text is html, and then note

Tag, src='cid:file','cid' is an acronym for contentId, and 'file' is a tag that needs to be replaced by a file helper.setText () by calling the addInline method of MimeMessageHelper in the following code

Hello Html Email

, true); FileSystemResource file = new FileSystemResource ("C:\ Users\ Public\ Pictures\ Sample Pictures\ Chrysanthemum.jpg"); helper.addInline ("file", file); mailSender.send (msg);}

4. Use the Velocity template to determine the email style.

To use the Velocity template, you need the jar package of Velocity, which can be downloaded from the official website and added to ClassPath. Then you need to declare a VelocityEngine object. For more information, please refer to the following code. This is the author's * use of Velocity. I don't know much about it. I'm sorry.

Declare a VelocityEngine object and initialize it in the constructor (IoC is optional)

... Parameter private VelocityEngine velocityEngine; public SpringMailSender () {. / / Velocity. Create VelocityEngine through VelocityEngineFactoryBean. It is also recommended to configure Properties props = System.getProperties (); props.put ("resource.loader", "class"); props.put ("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); VelocityEngineFactoryBean v = new VelocityEngineFactoryBean (); v.setVelocityProperties (props) in the configuration file. Try {velocityEngine = v.createVelocityEngine ();} catch (VelocityException e) {e.printStackTrace ();} catch (IOException e) {e.printStackTrace ();}}

Simple Velocity template file (index.vm):

H5 {color:red; background:#efefef;} ${user}

${content}

It seems easy to understand, but ordinary Html files use some ${placeholder} as placeholders.

All Java has to do is load the template and insert the corresponding value into the placeholder.

/ * send email using Velocity template * * @ throws MessagingException * / public void templateSend () throws MessagingException {/ / declare the Map object and fill in the key value pair Map model = new HashMap (); model.put ("user", "MZULE"); model.put ("content", "Hello") used to populate the template file / / the VelocityEngineUtils provided by Spring populates the template with data and converts it into a normal String object String emailText = VelocityEngineUtils.mergeTemplateIntoString (velocityEngine, "index.vm", model); / / the same MimeMessage msg = mailSender.createMimeMessage () as above; MimeMessageHelper helper = new MimeMessageHelper (msg, true); helper.setFrom (mailSender.getUsername ()); helper.setTo ("mosaic@126.com"); helper.setSubject ("Rich content mail") Helper.setText (emailText, true); mailSender.send (msg);}

Spring can be said to greatly simplify the steps to send mail, although our own packaging may not be complicated, but there is a ready-made, why re-create the wheel?

The above is the editor for you to share how to use Spring to make Java Mail support to simplify email sending, if you happen to have similar doubts, you might as well refer to the above analysis to understand. If you want to know more about it, you are welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report