Sunteți pe pagina 1din 8

Spring Java Mail Tutorial

Spring 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 API


The interfaces and classes for java mail support in spring framework are as follows:

1.MailSender interface: It is the root interface. It provides basic functionality for sending
simple mails.

2.JavaMailSender interface: It is the subinterface of MailSender. It supports MIME


messages. It is mostly used with MimeMessageHelper class for the creation of
JavaMail MimeMessage, with attachment etc. The spring framework
recommends MimeMessagePreparator mechanism for using this interface.

3.JavaMailSenderImpl class: It provides the implementation of JavaMailSender interface.


It supports JavaMail MimeMessages and Spring SimpleMailMessages.

4.SimpleMailMessage class: It is used to create a simple mail message including from, to,
cc, subject and text messages.
5.MimeMessagePreparator interface: It is the callback interface for the preparation of
JavaMail MIME messages.

6.MimeMessageHelper class: It is the helper class for creating a MIME message. It offers
support for inline elements such as images, typical mail attachments and HTML text content.

Example of Sending mail in Spring by Gmail Server


In this example, we are using two spring mail classes:

1.SimpleMailMessage for creating message.

2.JavaMailSenderImpl for sending message.


You need to create following files for sending email through Spring framework.

1.MailMail.java

2.applicationContext.xml

3.Test.java

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.

1. package com.javatpoint;
2. import org.springframework.mail.MailSender;
3. import org.springframework.mail.SimpleMailMessage;
4.
5. public class MailMail{
6. private MailSender mailSender;
7.
8. public void setMailSender(MailSender mailSender) {
9. this.mailSender = mailSender;
10. }
11.
12. public void sendMail(String from, String to, String subject, String msg) {
13. //creating message
14. SimpleMailMessage message = new SimpleMailMessage();
15. message.setFrom(from);
16. message.setTo(to);
17. message.setSubject(subject);
18. message.setText(msg);
19. //sending message
20. mailSender.send(message);
21. }
22.}

2) applicationContext.xml

In this xml file, we are creating a bean for JavaMailSenderImpl class. We need to define values of
following properties:

1.host

2.username

3.password

4.javaMailProperties
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.

1. <?xml version="1.0" encoding="UTF-8"?>


2. <beans
3. xmlns="http://www.springframework.org/schema/beans"
4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
5. xmlns:p="http://www.springframework.org/schema/p"
6. xsi:schemaLocation="http://www.springframework.org/schema/beans
7. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
8.
9. <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
10. <property name="host" value="smtp.gmail.com" />
11. <property name="username" value="yourgmailid@gmail.com" />
12. <property name="password" value="yourgmailpassword" />
13. <property name="javaMailProperties">
14. <props>
15. <prop key="mail.smtp.auth">true</prop>
16. <prop key="mail.smtp.socketFactory.port">465</prop>
17. <prop key="mail.smtp.socketFactory.class">javax.net.ssl.SSLSocketFactory</prop>
18. <prop key="mail.smtp.port">465</prop>
19. </props>
20. </property>
21.</bean>
22.<bean id="mailMail" class="com.javatpoint.MailMail">
23. <property name="mailSender" ref="mailSender" />
24.</bean>
25.</beans>

3) Test.java

This class gets the bean of mailMail from the applicationContext.xml file and calls the sendMail
method of MailMail class.

1. package com.javatpoint;
2. import org.springframework.beans.factory.*;
3. import org.springframework.beans.factory.xml.XmlBeanFactory;
4. import org.springframework.core.io.*;
5. public class Test {
6. public static void main(String[] args) {
7.
8. Resource r=new ClassPathResource("applicationContext.xml");
9. BeanFactory b=new XmlBeanFactory(r);
10.MailMail m=(MailMail)b.getBean("mailMail");
11.String sender="sendergmailid@gmail.com";//write here sender gmail id
12.String receiver="receiveremailid@gmail.com";//write here receiver id
13.m.sendMail(sender,receiver,"hi","welcome");
14.
15.System.out.println("success");
16.}
17.}

How to run this example


Load the spring jar files for core and java mail

Load the mail.jar and activation.jar

Change the username and password property in the applicationContext.xml file, specifying
your gmail id and password.

Change the sender gmail id and receivermail id in the Test.java file.


Compile and Run the Test class

Example of Sending mail in Spring by Server provided by


host provider
If 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:

mail.unitedsquaad.com for the host name. Change it.

a@unitedsquaad.com for the username. Change it.

xxxxx for the password. Change it.

1. <?xml version="1.0" encoding="UTF-8"?>


2. <beans
3. xmlns="http://www.springframework.org/schema/beans"
4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
5. xmlns:p="http://www.springframework.org/schema/p"
6. xsi:schemaLocation="http://www.springframework.org/schema/beans
7. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
8.
9. <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
10. <property name="host" value="mail.unitedsquaad.com" />
11. <property name="username" value="a@unitedsquaad.com" />
12. <property name="password" value="xxxxx" />
13.
14. <property name="javaMailProperties">
15. <props>
16. <prop key="mail.smtp.auth">true</prop>
17. </props>
18. </property>
19.
20.</bean>
21.<bean id="mailMail" class="MailMail">
22. <property name="mailSender" ref="mailSender" />
23.</bean>
24.
25.</beans>

Sending mails to multiple receivers


You 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.

1. ....
2. public void sendMail(String from, String[] to, String subject, String msg) {
3. //creating message
4. SimpleMailMessage message = new SimpleMailMessage();
5. message.setFrom(from);
6. message.setTo(to);//passing array of recipients
7. message.setSubject(subject);
8. message.setText(msg);
9. //sending message
10. mailSender.send(message);
11.}
12. ...

Spring MimeMessagePreparator Example


We 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.

1. import javax.mail.Message;
2. import javax.mail.internet.InternetAddress;
3. import javax.mail.internet.MimeMessage;
4. import org.springframework.mail.javamail.JavaMailSender;
5. import org.springframework.mail.javamail.MimeMessagePreparator;
6.
7. public class MailMail{
8. private JavaMailSender mailSender;
9.
10. public void setMailSender(JavaMailSender mailSender) {
11. this.mailSender = mailSender;
12. }
13.
14. public void sendMail(final String from, final String to,final String subject,final String msg) {
15.
16. MimeMessagePreparator messagePreparator = new MimeMessagePreparator() {
17.
18. public void prepare(MimeMessage mimeMessage) throws Exception {
19. mimeMessage.setRecipient(Message.RecipientType.TO,new InternetAddress(to));
20. mimeMessage.setFrom(new InternetAddress(from));
21. mimeMessage.setSubject(subject);
22. mimeMessage.setText(msg);
23. }
24. };
25. mailSender.send(messagePreparator);
26. }
27.}
The applicationContext.xml and Test.java files are same as given above.

Sending Attachment by Spring MimeMessageHelper


Example
We 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).

1. import java.io.File;
2. import javax.mail.MessagingException;
3. import javax.mail.internet.MimeMessage;
4. import org.springframework.core.io.FileSystemResource;
5. import org.springframework.mail.javamail.JavaMailSender;
6. import org.springframework.mail.javamail.MimeMessageHelper;
7.
8. public class MailMail{
9. private JavaMailSender mailSender;
10.
11. public void setMailSender(JavaMailSender mailSender) {
12. this.mailSender = mailSender;
13. }
14.
15. public void sendMail(final String from, final String to,final String subject,final String msg) {
16. try{
17. MimeMessage message = mailSender.createMimeMessage();
18.
19. MimeMessageHelper helper = new MimeMessageHelper(message, true);
20. helper.setFrom(from);
21. helper.setTo(to);
22. helper.setSubject(subject);
23. helper.setText(msg);
24.
25. // attach the file
26. FileSystemResource file = new FileSystemResource(new File("c:/rr.jpg"));
27. helper.addAttachment("mybrothermage.jpg", file);//image will be sent by this name
28.
29. mailSender.send(message);
30. }catch(MessagingException e){e.printStackTrace();}
31. }
32.}
The applicationContext.xml and Test.java files are same as given above.

S-ar putea să vă placă și