zoukankan      html  css  js  c++  java
  • 模板发送java邮件

    Creating email content using a templating library

    The code in the previous examples explicitly created the content of the email message, using methods calls such as message.setText(..). This is fine for simple cases, and it is okay in the context of the aforementioned examples, where the intent was to show you the very basics of the API.

    In your typical enterprise application though, you are not going to create the content of your emails using the above approach for a number of reasons.

    • Creating HTML-based email content in Java code is tedious and error prone
    • There is no clear separation between display logic and business logic
    • Changing the display structure of the email content requires writing Java code, recompiling, redeploying…​

    Typically the approach taken to address these issues is to use a template library such as FreeMarker or Velocity to define the display structure of email content. This leaves your code tasked only with creating the data that is to be rendered in the email template and sending the email. It is definitely a best practice for when the content of your emails becomes even moderately complex, and with the Spring Framework’s support classes for FreeMarker and Velocity becomes quite easy to do. Find below an example of using the Velocity template library to create email content.

    A Velocity-based example

    To use Velocity to create your email template(s), you will need to have the Velocity libraries available on your classpath. You will also need to create one or more Velocity templates for the email content that your application needs. Find below the Velocity template that this example will be using. As you can see it is HTML-based, and since it is plain text it can be created using your favorite HTML or text editor.

    # in the com/foo/package
    <html>
        <body>
            <h3>Hi ${user.userName}, welcome to the Chipping Sodbury On-the-Hill message boards!</h3>
    
            <div>
                Your email address is <a href="mailto:${user.emailAddress}">${user.emailAddress}</a>.
            </div>
        </body>
    </html>

    Find below some simple code and Spring XML configuration that makes use of the above Velocity template to create email content and send email(s).

    package com.foo;
    
    import org.apache.velocity.app.VelocityEngine;
    import org.springframework.mail.javamail.JavaMailSender;
    import org.springframework.mail.javamail.MimeMessageHelper;
    import org.springframework.mail.javamail.MimeMessagePreparator;
    import org.springframework.ui.velocity.VelocityEngineUtils;
    
    import javax.mail.internet.MimeMessage;
    import java.util.HashMap;
    import java.util.Map;
    
    public class SimpleRegistrationService implements RegistrationService {
    
        private JavaMailSender mailSender;
        private VelocityEngine velocityEngine;
    
        public void setMailSender(JavaMailSender mailSender) {
            this.mailSender = mailSender;
        }
    
        public void setVelocityEngine(VelocityEngine velocityEngine) {
            this.velocityEngine = velocityEngine;
        }
    
        public void register(User user) {
    
            // Do the registration logic...
    
            sendConfirmationEmail(user);
        }
    
        private void sendConfirmationEmail(final User user) {
            MimeMessagePreparator preparator = new MimeMessagePreparator() {
                public void prepare(MimeMessage mimeMessage) throws Exception {
                    MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
                    message.setTo(user.getEmailAddress());
                    message.setFrom("webmaster@csonth.gov.uk"); // could be parameterized...
                    Map model = new HashMap();
                    model.put("user", user);
                    String text = VelocityEngineUtils.mergeTemplateIntoString(
                            velocityEngine, "com/dns/registration-confirmation.vm", model);
                    message.setText(text, true);
                }
            };
            this.mailSender.send(preparator);
        }
    
    }
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans.xsd">
    
        <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
            <property name="host" value="mail.csonth.gov.uk"/>
        </bean>
    
        <bean id="registrationService" class="com.foo.SimpleRegistrationService">
            <property name="mailSender" ref="mailSender"/>
            <property name="velocityEngine" ref="velocityEngine"/>
        </bean>
    
        <bean id="velocityEngine" class="org.springframework.ui.velocity.VelocityEngineFactoryBean">
            <property name="velocityProperties">
                <value>
                    resource.loader=class
                    class.resource.loader.class=org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader
                </value>
            </property>
        </bean>
    
    </beans>

    附录:
    <dependency>
    	<groupId>org.apache.velocity</groupId>
    	<artifactId>velocity</artifactId>
    	<version>1.7</version>
    </dependency>
    

      

  • 相关阅读:
    Django学习【第5篇】:Django之ORM数据库操作注意细节
    Django学习【第5篇】:Django之ORM数据库操作
    Django学习【第4篇】:Django之模板继承
    Django学习【第3篇】:Django之模板语法
    Django学习【第2篇】:Django之反向解析
    Django学习【第1篇】:Django之MTV模型
    cookie和session
    Django 之 auth 模块
    Django 之 form表单
    中间件的流程图
  • 原文地址:https://www.cnblogs.com/kedarui/p/6647550.html
Copyright © 2011-2022 走看看