Khalifa
Khalifa

Reputation: 313

Sending mails from Web Application using Spring

In My Web application i want to send mails. Is There any way to do it with Spring MVC ? And what's the best way to do it ?

Thank you

Upvotes: 2

Views: 4628

Answers (3)

Xavi López
Xavi López

Reputation: 27880

You can use Spring's mail abstraction layer to easily send emails. Define the following beans in your applicationContext.xml

<!-- Mail sender bean -->
<bean id="mailSender" 
        class="org.springframework.mail.javamail.JavaMailSenderImpl">          
<property name="host" value="my.smtp.host" />
<property name="username" value="my_username" />
<property name="password" value="my_password" />
</bean>

<!-- Simple mail template -->
<bean id="basicEmailMessage" 
        class="org.springframework.mail.SimpleMailMessage">
    <property name="from">
        <value>whateverSenderAddress</value>
     </property>
 </bean>

 <!-- Your service with sender and template injected -->
 <bean id="mySendMailService" 
        class="mypackage.MySendMailService">
    <property name="mailSender">
    <ref bean="mailSender" />
    </property>
    <property name="emailTemplate">
        <ref bean="basicEmailMessage" />
    </property>
 </bean>

Then, in mypackage.MySendMailService:

public class SendMailService {
    private MailSender mailSender;
    private SimpleMailMessage emailTemplate;
    public void sendEmail(String to, String from, String subject, String body) 
                         throws MailException {
        SimpleMailMessage message = new SimpleMailMessage(this.emailTemplate);
        message.setTo(to);
        message.setFrom(from);
        message.setSubject(subject);
        message.setText(body);
        mailSender.send(message);
    }

    public void setMailSender(MailSender mailSender) {
        this.mailSender = mailSender;
    }
    public void setEmailTemplate(SimpleMailMessage emailTemplate) {
        this.emailTemplate = emailTemplate;
    }
}

Upvotes: 5

Robert M.
Robert M.

Reputation: 1367

I'm using Apache Velocity as E-Mail templating system. You can define an instance of "VelocityEngine" as a spring bean and inject it into your controllers. The much cleaner solution however is to put the mail-sending code into a service and inject your service into your controller.

 @Autowired private VelocityEngine velocityEngine;
     @Autowired private JavaMailSender mailSender;

        MimeMessagePreparator preparator = new MimeMessagePreparator() {
                    @Override
                    public void prepare(MimeMessage mimeMessage) throws Exception {
                        MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
                        message.setTo("[email protected]");
                        message.setFrom("[email protected]");
                        message.setSubject("You got mail!");

                                Map<String, Object> model = new HashMap<String, Object>();
                        model.put("param1", new Date());

                        String text = 
                            VelocityEngineUtils.mergeTemplateIntoString(
                                    velocityEngine, 
                                    "com/myapp/mailtemplates/email.vm", 
                                    model
                            );

                        mimeMessage.setText(text,"utf-8", "html");
                        mimeMessage.setHeader("Content-Type", "text/html; charset=utf-8");
                    }
                };

mailSender.send(preparator);

The HashMap can be used to pass parameters you can then use inside your velocity template. Then you can send your email using a "JavaMailSender" which can also be define as a spring bean.

You can define the mailSender and the velocityEngine beans similar to this:

    <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
        <property name="host" value="smtp.mail.com" />
        <property name="username" value="sender" />
        <property name="password" value="password" />
        <property name="javaMailProperties">
            <props>
                <!-- Use SMTP-AUTH to authenticate to SMTP server -->
                <prop key="mail.smtp.auth">true</prop>
                <!-- Use TLS to encrypt communication with SMTP server -->
                <!-- <prop key="mail.smtp.starttls.enable">true</prop> -->
            </props>
        </property>
    </bean>

    <!-- Apache Velocity Email Template Engine -->
    <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>

Upvotes: 3

Ryan Stewart
Ryan Stewart

Reputation: 128909

Spring MVC is a web framework, and it has nothing to do with email. Another part of the Spring framework does support mail sending though. Take a look at chapter 24 of the ref guide.

Upvotes: 1

Related Questions