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

Source: Internet
Author: User

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 class SpringMailSender {    // Spring的邮件工具类,实现了MailSender和JavaMailSender接口    private JavaMailSenderImpl mailSender;        public SpringMailSender() {    // 初始化JavaMailSenderImpl,当然推荐在spring配置文件中配置,这里是为了简单    mailSender = new JavaMailSenderImpl();    // 设置参数    mailSender.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

?
/** * 简单邮件发送 * */public void simpleSend() {    // 构建简单邮件对象,见名知意    SimpleMailMessage smm = new SimpleMailMessage();    // 设定邮件参数    smm.setFrom(mailSender.getUsername());    smm.setTo("[email protected]");    smm.setSubject("Hello world");    smm.setText("Hello world via spring mail sender");    // 发送邮件    mailSender.send(smm);}

  

2. Send mail with Attachments

?
/** * 带附件的邮件发送 * * @throws MessagingException */public void attachedSend() throws MessagingException {    //使用JavaMail的MimeMessage,支付更加复杂的邮件格式和内容    MimeMessage msg = mailSender.createMimeMessage();    //创建MimeMessageHelper对象,处理MimeMessage的辅助类    MimeMessageHelper helper = new MimeMessageHelper(msg, true);    //使用辅助类MimeMessage设定参数    helper.setFrom(mailSender.getUsername());    helper.setTo("[email protected]");    helper.setSubject("Hello Attachment");    helper.setText("This is a mail with attachment");    //加载文件资源,作为附件    ClassPathResource file = new ClassPathResource(            "Chrysanthemum.jpg");    //加入附件    helper.addAttachment("attachment.jpg", file);    //发送邮件    mailSender.send(msg);}

  

3. Send Rich Text mail

?
/**发送富文本邮件 * @throws MessagingException */public void richContentSend() throws MessagingException {    MimeMessage msg = mailSender.createMimeMessage();    MimeMessageHelper helper = new MimeMessageHelper(msg, true);    helper.setFrom(mailSender.getUsername());    helper.setTo("[email protected]");    helper.setSubject("Rich content mail");    //第二个参数true,表示text的内容为html,然后注意标签,src=‘cid:file‘,‘cid‘是contentId的缩写,‘file‘是一个标记,需要在后面的代码中调用MimeMessageHelper的addInline方法替代成文件    helper.setText(            "<body><p>Hello Html Email</p></body>",            true);    FileSystemResource file = new FileSystemResource(            "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)

?
...private VelocityEngine velocityEngine;public SpringMailSender() {        ...    // Velocity的参数,通过VelocityEngineFactoryBean创建VelocityEngine,也是推荐在配置文件中配置的    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);    try {        velocityEngine = v.createVelocityEngine();    } catch (VelocityException e) {        e.printStackTrace();    } catch (IOException e) {        e.printStackTrace();    }}

Simple velocity template file (INDEX.VM):

?
<html><head><style type="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.

?
/** * 使用Velocity模板发送邮件 * * @throws MessagingException */public void templateSend() throws MessagingException {    // 声明Map对象,并填入用来填充模板文件的键值对    Map<String, String> model = new HashMap<String, String>();    model.put("user", "MZULE");    model.put("content", "Hello");    // Spring提供的VelocityEngineUtils将模板进行数据填充,并转换成普通的String对象    String emailText = VelocityEngineUtils.mergeTemplateIntoString(            velocityEngine, "index.vm", model);    // 和上面一样的发送邮件的工作    MimeMessage msg = mailSender.createMimeMessage();    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);}

Spring is a great simplification of the message delivery process, although our own encapsulation may not be complex to implement, but there is a ready-made need to reinvent the wheel? (Of course, you can learn a lot of wheels)

<properties>
<springframework.version>3.0.5.RELEASE</springframework.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

Http://www.cnblogs.com/codeplus/archive/2011/11/03/2232893.html

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.