Enlightensoft's Blog

Helping in your each step

  • Categories

  • Authors

Send Mail Using Spring

Posted by Pankil Patel on August 22, 2010

Step 1:
Create a class named “MailService”

package co.cc.enlightensoft.service.mail;

import javax.mail.internet.MimeMessage;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;

public class MailService {
private static final Log LOG = LogFactory.getLog(MailService.class);
private JavaMailSenderImpl mailSender;
public void setMailSender(JavaMailSenderImpl mailSender) {
this.mailSender = mailSender;
}

public void sendMail(String from, String[] to, String subject, StringBuffer content) {
try {
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(content.toString());
mailSender.send(message);
LOG.info(“Mail has been sent.”);
} catch (Exception ex) {
System.err.println(ex.getMessage());
LOG.error(“Exception while sending mail…” + ex.getMessage());
}
}
}

Step 2:
Create Two Spring Bean (1) mailSender and Use this bean into (2) mailService which is based on created file in step 1

<bean id=”mailSender” class=”org.springframework.mail.javamail.JavaMailSenderImpl”>
<property name=”host” value=”192.168.1.1″ />
</bean>
<bean name=”mailService”>
<property name=”mailSender” ref=”mailSender” />
</bean>

Step 3:
Use “mailService” Spring Bean into your service as a property injection to send email

Goooooooooooooooooooooood Luck…….. Enjoyeeeeeeeeeeeeeeeeeeeeeee…………

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: