Showing posts with label Email. Show all posts
Showing posts with label Email. Show all posts

Spring - Sending E-Mail with MailSender

 
Sending email using Spring "org.springframework.mail.javamail.JavaMailSenderImpl" class simplifies the process with JavaMail API. Below example will give step by step to send email by using Gmail SMTP server configurations.

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 <modelVersion>4.0.0</modelVersion>
 <groupId>org.springframework.samples</groupId>
 <artifactId>SendingEmail</artifactId>
 <version>0.0.1-SNAPSHOT</version>

 <dependencies>

  <!-- Spring framework -->
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring</artifactId>
   <version>2.5.6.SEC03</version>
  </dependency> 

  <!-- Java Mail API -->
  <dependency>
   <groupId>javax.mail</groupId>
   <artifactId>mail</artifactId>
   <version>1.4.3</version>
  </dependency>

 </dependencies>
</project>

email.xml

<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

 <bean id="emailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
  <property name="host" value="smtp.gmail.com" />
  <property name="port" value="587" />
  <property name="username" value="USERNAME" />
  <property name="password" value="PASSWORD" />

  <property name="javaMailProperties">
   <props>
    <prop key="mail.smtp.auth">true</prop>
    <prop key="mail.smtp.starttls.enable">true</prop>
   </props>
  </property>
 </bean>

 <bean id="emailBean" class="com.app.email.Mailer">
  <property name="emailSender" ref="emailSender" />
 </bean>

</beans>

Mailer.java

package com.app.email;

import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;

public class Mailer {

 private MailSender emailSender;
 
 //Setter for emailSender
 public void setEmailSender(MailSender emailSender) {
  this.emailSender = emailSender;
 }
 
 //Method to send email
 public void sendMail(String from, String to, String subject, String msg) {

  SimpleMailMessage simpleMsg = new SimpleMailMessage();
  
  simpleMsg.setFrom(from);
  simpleMsg.setTo(to);
  simpleMsg.setSubject(subject);
  simpleMsg.setText(msg);
  
  //Finally sending email using MailSender
  emailSender.send(simpleMsg); 
 }
}

SendEmail.java

package com.app.email;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SendEmail {

 public static void main(String[] args) {

  String from = "from@gmail.com";
  String to = "to@gmail.com";
  String subject = "Hello World !";
  String msg = "Hello World, How are you ???";

  ApplicationContext context = new ClassPathXmlApplicationContext("email.xml");

  try {
   Mailer mailer = (Mailer) context.getBean("emailBean");
   mailer.sendMail(from, to, subject, msg);

  } catch (Exception e) {
   e.printStackTrace();
  }
 }
}


Spring - Sending E-Mail with MailSender


Sending email using Java Mail API

In this tutorial we will see how to send email using Java Mail API. We are using Gmail SMTP host for sending email in the below sample code.
Mainly we need 2 jar files to implement Java Mail API. Those jar's are

  • activation-1.0.2.jar
  • mail-1.4.1.jar

Below code have tested along with above jar files. 



import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class SendEmailViaGmail {
 public static void main(String[] args) {
  
  // To address
  String to = "to@gmail.com";
  // If any CC email ids
  String cc = "cc@abcmail.com";
  // If any BCC email ids
  String bcc = "bcc@abcmail.com";
  // Email Subject
  String subject = "Java Discover";
  // Email content
  String emailText = "Hi All, Welcome to Java Discover";

  // Sending Email using Gmail SMTP
  sendEmail(to, cc, bcc, subject, emailText);
 }

 public static void sendEmail(String to, String cc, String bcc, String subject, String emailText) {
  
  // From address (Need Gmail ID)
  String from = "from@gmail.com";
  // Password of from address
  String password = "frompassword";
  // Gmail host address
  String host = "smtp.gmail.com";
  
  Properties props = System.getProperties();
  props.put("mail.smtp.host", host);
  props.put("mail.smtp.socketFactory.port", "465");
  props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
  props.put("mail.smtp.auth", "true");
  props.put("mail.smtp.port", "465");
  props.put("mail.smtp.user", from);
  props.put("password", password);

  Session session = Session.getDefaultInstance(props, null);

  MimeMessage msg = new MimeMessage(session);
  try {
   msg.setFrom(new InternetAddress(from));
   
   // Adding To address
   msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
   // Adding CC email id
   msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false));
   // Adding BCC email id
   msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false));

   msg.setSubject(subject);
   msg.setText(emailText);
   
   Transport transport = session.getTransport("smtp");
   transport.connect(host, from, password);
   transport.sendMessage(msg, msg.getAllRecipients());
   transport.close();
   
   System.out.println("Email sent successfully.....");
   
  } catch (AddressException e) {
   e.printStackTrace();
  } catch (MessagingException e) {
   e.printStackTrace();
  }
 }
}



IMP:
Suppose if you are getting exception while running above like,

javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

then valid SSL certificate is missing in the machine which your running. Follow the steps given in link and try again.