send a message using freemarker

2.3k views Asked by At

I need to send a letter with the body:

 Lector {LectorName} had created a new course
 ----------------------------------------------------
 Name:        {CourseName}
 Category:    {CourseCategory}
 Description: {CourseDescription}
 Links:       {CourseLinks}
 ----------------------------------------------------
 Please, review this course at {CourseApproveLink}

I made on a page freemarker

<!DOCTYPE html>
<html lang="en">
 <head>

</head>
<body>

<p>         ${LectorName} had created a new course</p>
<p>----------------------------------------------------</p>
<p>Name: ${Course.title}</p>
<p>Category: ${Course.category.name}</p>
<p>Description: ${Course.descr}</p>
 <p>Links: ${Course.links}</p>
 <p>----------------------------------------------------</p>
  <p>Please, review this course at ${CourseApproveLink}</p>
  </body>
   </html>

how to fill it and pass the values in the method of sending the letter? Here is my code. My method sendMail and Bean "mailSender" with my settings. It is necessary to do so new MimeMessage(session) ? How do I get the settings from the bean into the session?

@Service("mailService")
public class MailService {

@Autowired
private MailSender mailSender;
@Autowired
private SimpleMailMessage alertMailMessage;

@Resource(name = "freemarkerEmailConfig")
private Configuration emailConfiguration;

public void sendMail(String from, String to, String subject, String body) {

SimpleMailMessage message = new SimpleMailMessage();

message.setFrom(from);
message.setTo(to);
message.setSubject(subject);
 message.setText(body);

mailSender.send(message);

}

public void sendAlertMail(String alert) {

SimpleMailMessage mailMessage = new SimpleMailMessage(alertMailMessage);
mailMessage.setText(alert);
mailSender.send(mailMessage);

}

}



<bean id="mailSender"  class="org.springframework.mail.javamail.JavaMailSenderImpl">

    <property name="host" value="smtp.mail.ru" />
    <property name="port" value="465" />
    <property name="username" value="[email protected]" />
    <property name="password" value="***********" />
    <property name="javaMailProperties">
        <props>
            <prop key="mail.transport.protocol">smtp</prop>
            <prop key="mail.smtp.auth">true</prop>
            <prop key="mail.smtp.ssl.enable">true</prop>
            <prop key="mail.debug">true</prop>
        </props>
    </property>
    </bean>

    <bean id="alertMailMessage"  class="org.springframework.mail.SimpleMailMessage">
    <property name="from">
        <value>[email protected]</value>
    </property>
    <property name="to">
        <value>[email protected]</value>
    </property>
    <property name="subject"
        value="Alert - Exception occurred. Please investigate" />

    </bean>
1

There are 1 answers

9
Tony Vu On

You need to pass in a map to the method that sends email with freemarker template. In your case the map will look something like:

Map<Object, Object> map = new HashMap<Object, Object>();
map.put("LectorName", "...");
map.put("Course", course);
map.put("CourseApproveLink", "...");

Freemarker will resolve variable names based on the keys you passed in.

If you use Spring, then configure the template directory in applicationContext.xml like this:

<!-- FreeMarker Configuration -->
<bean id="freemarkerEmailConfig" class="freemarker.template.Configuration">
    <property name="directoryForTemplateLoading" value="templates/email" />
    <property name="objectWrapper">
        <bean class="freemarker.template.DefaultObjectWrapper"/>
    </property>
</bean> 

Put your template under templates/email folder (relative to your webapp). Inject the freemarkerEmailConfig bean defined in applicationContext into your service class:

@Resource(name = "freemarkerEmailConfig")
private Configuration emailConfiguration;

Now in your service class you can use emailConfiguration to retrieve the template and then process it with the map above like this:

Template template = emailConfiguration.getEmailTemplate(templateName);
String text = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);

FreeMarkerTemplateUtils is a class from Spring. Now text will contain the html with the all the variables substituted by values from the map. Just send the email with text as html content:

MimeMessage msg = mailSender.createMimeMessage();
msg.setFrom(new InternetAddress(EMAIL_SENDER_ADDRESS, EMAIL_SENDER_PERSONAL));
msg.setSubject(subject);
msg.setSentDate(new Date());
msg.setContent(text, "text/html; charset=UTF-8");
for (EmailInternetAddress emailInternetAddress  :emailInternetAddresses) {
    msg.addRecipient(emailInternetAddress.getRecipientType(),
                emailInternetAddress.getInternetAddress());
    }
mailSender.send(msg);