Spring comes with a useful ‘org.springframework.mail.javamail.JavaMailSenderImpl‘ class to simplify the e-mail sending process via JavaMail API. Here’s a Maven build project to use Spring’s ‘JavaMailSenderImpl‘ to send an email via Gmail SMTP server.
1. Project dependency
Add the JavaMail and Spring’s dependency.
File : pom.xml
4.0.0 com.mkyong.common SpringExample jar 1.0-SNAPSHOT SpringExample http://maven.apache.org Java.Net http://download.java.net/maven/2/ junit junit 3.8.1 test javax.mail 1.4.3 org.springframework spring 2.5.6
2. Spring’s Mail Sender
A Java class to send email with the Spring’s MailSender interface.
File : MailMail.java
package com.mkyong.common; import org.springframework.mail.MailSender;import org.springframework.mail.SimpleMailMessage; public class MailMail{ private MailSender mailSender; public void setMailSender(MailSender mailSender) { this.mailSender = mailSender; } public void sendMail(String from, String to, String subject, String msg) { SimpleMailMessage message = new SimpleMailMessage(); message.setFrom(from); message.setTo(to); message.setSubject(subject); message.setText(msg); mailSender.send(message); }}
3. Bean configuration file
Configure the mailSender bean and specify the email details for the Gmail SMTP server.
Note Gmail configuration details –
File : Spring-Mail.xml
true true
4. Run it
package com.mkyong.common; import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext; public class App { public static void main( String[] args ) { ApplicationContext context = new ClassPathXmlApplicationContext("Spring-Mail.xml"); MailMail mm = (MailMail) context.getBean("mailMail"); mm.sendMail("from@no-spam.com", "to@no-spam.com", "Testing123", "Testing only \n\n Hello Spring Email Sender"); }}
referenc from:http://www.mkyong.com/spring/spring-sending-e-mail-via-gmail-smtp-server-with-mailsender/