Add your dependencies
Add spring-context-support and javax.mail dependencies to your project
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>3.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.5.5</version>
</dependency>
Make your SMPTP your MailSender Object
Go to your bean definitions and add the following bean :
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="port"><value>465</value></property>
<property name="protocol"><value>smtp</value></property>
<property name="username"><value>youremail</value></property>
<property name="password"><value>password</value></property>
<property name="javaMailProperties">
<props>
<prop key="mail.smtp.auth">true</prop>
<prop key="mail.smtp.starttls.enable">false</prop>
<prop key="mail.smtp.quitwait">false</prop>
<prop key="mail.smtp.socketFactory.class">javax.net.ssl.SSLSocketFactory</prop>
<prop key="mail.smtp.socketFactory.fallback">false</prop>
<prop key="mail.debug">true</prop>
</props>
</property>
<prop key="mail.smtp.auth">true</prop>
<prop key="mail.smtp.starttls.enable">false</prop>
<prop key="mail.smtp.quitwait">false</prop>
<prop key="mail.smtp.socketFactory.class">javax.net.ssl.SSLSocketFactory</prop>
<prop key="mail.smtp.socketFactory.fallback">false</prop>
<prop key="mail.debug">true</prop>
</props>
</property>
</bean>
Send your mail with MailSender
Now, all you need to do is to prepare your mail message object and send it using a MailSender instance :
@Service
public class WorkbookMailSender {
@Autowired
private MailSender mailSender;
public void sendMail(String to, String subject, String message) { SimpleMailMessage mailMessage = new SimpleMailMessage(); mailMessage.setSubject(subject); mailMessage.setTo(to); mailMessage.setText(message); mailMessage.setSentDate(new Date());
this.mailSender.send(mailMessage);
}
}
That's it.