- The base package from which the context scanning will start is declared and is set to "com.javacodegeeks.spring.mail".
- The "mailSender" bean is declared and a bunch of its properties are appropriately set (use your own SMTP server configuration attributes and credentials).
- The "alertMailMessage" is a preconfigured Spring SimpleMailMessage and this will be injected in the "MailService" class using "by name autowiring".
In case you wish to use Gmail's SMTP server, make sure that the following JavaMail properties are configured appropriately:
1 | host=smtp.gmail.com |
2 | port=25 |
3 | username=your-gmail-username |
4 | password=your-gmail-password |
5 | mail.transport.protocol=smtp |
6 | mail.smtp.auth= true |
7 | mail.smtp.starttls. enable = true |
While in development phase, set "mail.debug" to true if you want the mail client to generate informative logs. However, remember to set this to false when in production, because the amount of logs could degrade the application's performance and/or fill-up your hard disks.
Finally, we create a class that will be used to create the Spring container and test the simple mail service we created. The source code is the following:
01 | package com.javacodegeeks.spring.mail; |
02 |
03 | import org.springframework.context.ApplicationContext; |
04 | import org.springframework.context.support.FileSystemXmlApplicationContext; |
05 |
06 | public class MailServiceTest { |
07 |
08 | public static void main(String[] args) { |
09 | |
10 | ApplicationContext context = new FileSystemXmlApplicationContext( "conf/spring.xml" ); |
11 |
12 | MailService mailService = (MailService) context.getBean( "mailService" ); |
13 | |
14 | mailService.sendMail( "myusername@gmail.com" , "myusername@gmail.com" , "Testing123" , "Testing only \n\n Hello Spring Email Sender" ); |
15 | |
16 | mailService.sendAlertMail( "Exception occurred" ); |
17 | |
18 | } |
19 | |
20 | } |
The FileSystemXmlApplicationContext class is used as the ApplicationContext. We pass the Spring's XML file location in the constructor and the class creates the container, instantiates the beans and takes care of the dependencies. Don't you love Spring? Next, we retrieve a reference of our "MailService" service using the "getBean" method and invoke the two methods.
That's all. As always, you can download the full Eclipse project from here.
Read more: Java Code Geeks: Sending e-mails in Java with Spring – GMail SMTP server example http://www.javacodegeeks.com/2010/07/java-mail-spring-gmail-smtp.html#ixzz0vF2sFGui
No comments:
Post a Comment