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
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With