dao.Mailer.java Source code

Java tutorial

Introduction

Here is the source code for dao.Mailer.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package dao;

import java.util.Date;
import javax.mail.internet.MimeMessage;
import javax.servlet.ServletContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

/**
 *
 * @author Phan Ba Hai
 */
@Service("mailer")
public class Mailer {

    @Autowired
    JavaMailSender mailer;
    @Autowired
    ServletContext context;

    public void send(String from, String to, String subject, String body) {
        try {
            MimeMessage mail = mailer.createMimeMessage();

            MimeMessageHelper helper = new MimeMessageHelper(mail, true);
            helper.setFrom(from, from);
            helper.setTo(to);
            helper.setReplyTo(from, from);
            helper.setSubject(subject);
            helper.setText(body, true);
            helper.setSentDate(new Date());

            mailer.send(mail);
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }
}