Use the freemaker or vilocity template in spring to send emails

Source: Internet
Author: User

This article describes how to use freemaker or vilocity in spring to send an email by sending an email to the user after the user registers.

Spring configuration file:
<! -- Use mail sender encapsulated by spring -->
<Bean id = "mailsender" class = "org. springframework. Mail. javamail. javamailsenderimpl">
<Property name = "host" value = "smtp.163.com"/>
<Property name = "username" value = "test"/>
<Property name = "password" value = "123456"/>
<Property name = "javamailproperties">
<Props>
<Prop key = "mail. SMTP. Auth"> true </prop>
</Props>
</Property>
</Bean>

<! -- Freemarker config -->
<Bean id = "freemarkerconfigurer" class = "org. springframework. Web. servlet. View. freemarker. freemarkerconfigurer">
<Property name = "templateloaderpath" value = "/WEB-INF/freemakertemplate/"/>
<Property name = "freemarkersettings">
<Props>
<Prop key = "template_update_delay"> 0 </prop>
<Prop key = "default_encoding"> GBK </prop>
<Prop key = "locale"> zh_cn </prop>
</Props>
</Property>
</Bean>

<! -- Vilocity config -->
<Bean id = "velocityengine" class = "org. springframework. UI. Velocity. velocityenginefactorybean">
<Property name = "resourceloaderpath" value = "/WEB-INF/vilocitytemplate/"/>
<Property name = "velocityproperties">
<Props>
<Prop key = "velocimacro. Library"> *. VM </prop>
<Prop key = "Default. contenttype"> text/html, charset = UTF-8 </prop>
<Prop key = "output. encoding"> UTF-8 </prop>
<Prop key = "input. encoding"> UTF-8 </prop>
</Props>
</Property>
</Bean>

<Bean id = "mailmessage" class = "org. springframework. Mail. simplemailmessage" Singleton = "false">
<Property name = "from" value = "test@163.com"/>
</Bean>

<Bean id = "mailengine" class = "test. mailengine">
<Property name = "mailsender" ref = "mailsender"/>
<! -- If you use vilocity -->
<Property name = "velocityengine" ref = "velocityengine"/>
<! -- If freemaker is used -->
<Property name = "freemarkerconfigurer" ref = "freemarkerconfigurer"/>
</Bean>

 
Mailengine class:

Public class mailengine {
Protected static final log = logfactory. getlog (mailengine. Class );

// Private freemarkerconfigurer;
Private velocityengine;
Private mailsender;

// Public void setfreemarkerconfigurer (
// Freemarkerconfigurer ){
// This. freemarkerconfigurer = freemarkerconfigurer;
//}

Public void setmailsender (mailsender ){
This. mailsender = mailsender;
}

Public void setvelocityengine (velocityengine ){
This. velocityengine = velocityengine;
}

/**
* Generate the mail body using the template
* @ Param templatename: email Template Name
* @ Param map refers to the object to be filled in the template
* @ Return mail body (HTML)
*/
Public String generateemailcontent (string templatename, map ){
// Use the freemaker Template
// Try {
// Configuration = freemarkerconfigurer. getconfiguration ();
// Template T = configuration. gettemplate (templatename );
// Return freemarkertemplateutils. processtemplate1_string (T, MAP );
//} Catch (templateexception e ){
// Log. Error ("error while processing freemarker template", e );
//} Catch (filenotfoundexception e ){
// E. printstacktrace ();
/// Log. Error ("error while open template file", e );
//} Catch (ioexception e ){
// Log. Error ("error while generate email content", e );
//}

// Use the vilocity Template
Try {
Return velocityengineutils. mergetemplate1_string (velocityengine, templatename, MAP );
} Catch (velocityexception e ){
Log. Error ("error while processing vilocity template", e );
}

Return NULL;
}

/**
* Send an email
* @ Param emailaddress: array of recipient email addresses
* @ Param fromemail sender email address, null is the default sender web@vnvtrip.com
* @ Param bodytext: Body of the email
* @ Param subject: Email Subject
* @ Param attachmentname: attachment name
* @ Param resource attachment
* @ Throws messagingexception
*/
Public void sendmessage (string [] emailaddresses, string fromemail,
String bodytext, string subject, string attachmentname,
Classpathresource Resource) throws messagingexception {
Mimemessage message = (javamailsenderimpl) mailsender)
. Createmimemessage ();

// Use the true flag to indicate you need a multipart message
Mimemessagehelper helper = new mimemessagehelper (message, true );

Helper. setto (emailaddresses );
If (fromemail! = NULL ){
Helper. setfrom (fromemail );
}
Helper. settext (bodytext, true );
Helper. setsubject (subject );

If (attachmentname! = NULL & Resource! = NULL)
Helper. addattachment (attachmentname, resource );

(Javamailsenderimpl) mailsender). Send (Message );
}

/**
* Send a simple email
* @ Param msg
*/
Public void send (simplemailmessage MSG ){
Try {
(Javamailsenderimpl) mailsender). Send (MSG );
} Catch (mailexception ex ){
// Log it and go on
Log. Error (ex. getmessage ());
}
}

/**
* Use a template to send an HTML-format email
*
* @ Param MSG is installed with simplemailmessage of to, from, and subject information.
* @ Param templatename: Template Name. The template root path is defined in freemakarengine in the configuration file.
* @ Param model the data required for rendering the Template
*/
Public void send (simplemailmessage MSG, string templatename, map model ){
// Generate HTML mail content
String content = generateemailcontent (templatename, model );
Mimemessage mimemsg = NULL;
Try {
Mimemsg = (javamailsenderimpl) mailsender). createmimemessage ();
Mimemessagehelper helper = new mimemessagehelper (mimemsg, true, "UTF-8 ");
Helper. setto (msg. getto ());

If (msg. getsubject ()! = NULL)
Helper. setsubject (msg. getsubject ());

If (msg. getfrom ()! = NULL)
Helper. setfrom (msg. getfrom ());

Helper. settext (content, true );

(Javamailsenderimpl) mailsender). Send (mimemsg );
} Catch (messagingexception ex ){
Log. Error (ex. getmessage (), Ex );
}

}
}

Send Email:
Simplemailmessage message = (simplemailmessage) getbean ("mailmessage ");
Message. setto (user. getname () + "<" + User. getemail () + "> ");

Map <string, user> model = new hashmap <string, user> ();
Model. Put ("user", user );

Mailengine engine = (mailengine) getbean ("mailengine ");
// Vilocity Template
Engine. Send (message, "yyuser. VM", model );
// Freemaker Template
// Engine. Send (message, "policyuser. FTL", model );

The preceding user is a user class.

Vilocity template:
Hello, $ {user. name! You have successfully registered as a member of this Site. Your information is as follows:

$ {User. name}
$ {User. Password}

Freemaker template:
<HTML>
<Head>
<Meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8">
<Title> User Registration notification </title>
</Head>
<Body>
<P> $ {user. name} Hello, congratulations! You have become a member of this site! </P>
<Table>
<Tr> <TD> User name: </TD> <TD >$ {user. name} </TD> </tr>
<Tr> <TD> password: </TD> <TD >$ {user. Password} </TD> </tr>
</Table>
</Body>
</Html>

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.