91-9990449935 0120-4256464 |
Spring Java Mail TutorialSpring framework provides many useful interfaces and classes for sending and receiving mails. The org.springframework.mail package is the root package that provides mail support in Spring framework. Spring Java Mail APIThe interfaces and classes for java mail support in spring framework are as follows:
Example of Sending mail in Spring by Gmail ServerIn this example, we are using two spring mail classes:
You need to create following files for sending email through Spring framework.
You need to load mail.jar and activation.jar files to run this example.download mail.jar and activation.jar or go to the Oracle site to download the latest version. 1) MailMail.java It is the simple class that defines mailSender property. An object of MailSender will be provided to this property at runtime. In the sendMail() method, we are creating the instance of SimpleMailMessage and storing the information into this object such as from, to, subject and message. The send() method of MailSender interface is used here to send the simple mail. 2) applicationContext.xml In this xml file, we are creating a bean for JavaMailSenderImpl class. We need to define values of following properties:
We are also creating the bean for MailMail class with mailSender property. Now, the instance of JavaMailSenderImpl class will be set in the mailSender property of MailMail class. 3) Test.java This class gets the bean of mailMail from the applicationContext.xml file and calls the sendMail method of MailMail class. How to run this example
Example of Sending mail in Spring by Server provided by host providerIf you have your own site, you can use your mail server. The MailMail.java and Test class will be same. You need to change only Sender email id in the Test.java file. Some changes are required in the applicationContext.xml file. In the applicationContext.xml file, we are using:
Sending mails to multiple receiversYou can send mails to multiple receivers by the help of SimpleMailMessage class. The setTo(String[] receivers) method of SimpleMailMessage class is used to send message to multiple receivers. Let's see the simple code. Spring MimeMessagePreparator ExampleWe can send the mime message by the help of MimeMessagePreparator interface. It has one method prepare(MimeMessage message). Let's see the simple code to send mime message. The applicationContext.xml and Test.java files are same as given above. Sending Attachment by Spring MimeMessageHelper ExampleWe can send the mime message with attachment in spring by the help of MimeMessageHelper class. It is recommended to use than MimeMessagePreparator. Let's see the simple code to send mime message with attachment(image). The applicationContext.xml and Test.java files are same as given above.
Next TopicSpring and Struts 2 Integration Example
|