Sending E-Mail
1. Create a Java Project named StandAloneEmail, convert it into the maven project
and make sure it has following pom.xml file
<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>StandAloneEmail</groupId>
<artifactId>StandAloneEmail</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<org.springframework.version>4.2.5.RELEASE</org.springframework.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-
context-support -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4</version>
</dependency>
</dependencies>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
2. Create a package named mailservice inside src package and create a Java file
named MySimpleMailService.java inside it
package mailservice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
@Service("mailService")
public class MySimpleMailService {
@Autowired
private MailSender mailSender;
@Autowired
private SimpleMailMessage preConfiguredMessage;
/**
* This method will send compose and send the message
* */
public void sendMail(String to, String subject, String body)
{
SimpleMailMessage message = new SimpleMailMessage();
message.setTo(to);
message.setSubject(subject);
message.setText(body);
mailSender.send(message);
}
/**
* This method will send a pre-configured message
* */
public void sendPreConfiguredMail(String message)
{
SimpleMailMessage mailMessage = new
SimpleMailMessage(preConfiguredMessage);
mailMessage.setText(message);
mailSender.send(mailMessage);
}
}
3. Create application context file named mail-context.xml inside StandAloneEmail
project.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- You can have some pre-configured messagess also which are ready
to send -->
<bean id="preConfiguredMessage"
class="org.springframework.mail.SimpleMailMessage">
<property name="to" value="[email protected]"></property>
<property name="from"
value="[email protected]"></property>
<property name="subject" value="FATAL - Application crash. Save
your job !!"/>
</bean>
</beans>
4. Create a package named testpro inside src and create TestApp.java inside it
package testpro;
import org.springframework.context.ApplicationContext;
import
org.springframework.context.support.FileSystemXmlApplicationContext;
import mailservice.MySimpleMailService;
package mailservice;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.MailParseException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
try{
MimeMessageHelper helper = new
MimeMessageHelper(message, true);
helper.setFrom(simpleMailMessage.getFrom());
helper.setTo(simpleMailMessage.getTo());
helper.setSubject(simpleMailMessage.getSubject());
helper.setText(String.format(
simpleMailMessage.getText(), dear, content));
<bean id="mailSender"
class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="smtp.gmail.com" />
<property name="port" value="587" />
<property name="username" value="[email protected]" />
<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="customeMailMessage"
class="org.springframework.mail.SimpleMailMessage">
package testpro;
import org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicationContext;
import mailservice.MyAttachmentMailService;
MyAttachmentMailService mm = (MyAttachmentMailService)
context.getBean("mailMail");
mm.sendMail("Mukesh Regmi", "Your E-Mail Content is: ");
}
}
5. Right Click TestAppAttachment.java-> Run As-> Java Application
Sending Email using Java EE Mail Session
We will use the same project above “StandAloneEmail” to send email using Java EE
Mail Session.
1. Create a java file named JavaEESessionDemo.java inside testpro package
package testpro;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class JavaEESessionDemo {
public String sendmail(String rcptmail,String person_name)
{
try
{
/////////////////////////////////////////
final String username = "[email protected]";
final String password = "#yourgmailpassword";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication
getPasswordAuthentication() {
return new
PasswordAuthentication(username, password);
}
});
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(rcptmail));
message.setSubject("Java EE Session Demo
Message");
/*message.setText("Dear Mail Crawler,"
+ "\n\n No spam to my email,
please!");*/
StringBuilder sb = new StringBuilder();
sb.append("<div>");
sb.append("<p> Hi,"+person_name+",</p><br>
You are most Welcome..!<br>");
sb.append("</body>");
sb.append("</html>");
////////////////
message.setContent(sb.toString(), "text/html"
);
Transport.send(message);
System.out.println("Message Sent");
return "ok";
//System.out.println(sb.toString());
/////////////////////////////////////////
}
catch(Exception e)
{
e.printStackTrace();
return "Even Though Confirmation E-Mail cannot be
Sent Due to Some Technical Reason, Your Order has now Been Confirmed !";
}
}
public static void main(String[] args) {
JavaEESessionDemo obj=new JavaEESessionDemo();
obj.sendmail("[email protected]", "Mukesh");
Similarly, inside context.xml as well, locate the <context> </context> tag and within it
add the above code.
At last, within web.xml and within <web-app> </web-app> tag, add following codes:
<resource-ref>
<description>Email Session</description>
<res-ref-name>mail/SessionChanged</res-ref-name>
<res-type>javax.mail.Session</res-type>
<res-auth>Container</res-auth>
</resource-ref>
Copy and paste mail-1.4 jar file inside Tomcat Installation lib directory from maven
location C:\Users\user\.m2\repository\javax\mail\mail\1.4
<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>ReusingEmailSession</groupId>
<artifactId>ReusingEmailSession</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<org.springframework.version>4.2.5.RELEASE</org.springframework.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-
context-support -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.tomcat/juli -->
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>juli</artifactId>
<version>6.0.45</version>
</dependency>
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>2.6</version>
<configuration>
<warSourceDirectory>WebContent</warSourceDirectory>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
package mycontroller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
import java.util.Properties;
import javax.mail.Authenticator;
@Controller
public class HelloController {
public HelloController()
{
System.out.println("Demo Controller");
}
@RequestMapping("/welcome")
public ModelAndView helloWorld() {
try
{
// Get the session and its properties from Tomcat's
server.xml, context.xml and web.xml file
System.setProperty(Context.INITIAL_CONTEXT_FACTORY,"org.apache.
naming.java.javaURLContextFactory");
String content="My Content";
Context initContext = new InitialContext();
Context context = (Context)
initContext.lookup("java:comp/env");
Session mailsession = (Session)
context.lookup("mail/SessionChanged");
Properties prop=mailsession.getProperties();
/*System.out.println("Smtp Server
name="+prop.getProperty("mail.smtp.host"));
System.out.println("Smtp User
Name="+prop.getProperty("username"));
System.out.println("Smtp
Password="+prop.getProperty("pwd"));
System.out.println("Smtp
Port="+prop.getProperty("mail.smtp.port"));*/
Session mailSession = mailsession.getInstance(prop,
new javax.mail.Authenticator() {
protected PasswordAuthentication
getPasswordAuthentication() {
return new
PasswordAuthentication(prop.getProperty("username"),
prop.getProperty("pwd"));
}
});
Message message = new MimeMessage(mailSession);
message.setFrom(new
InternetAddress("[email protected]"));
InternetAddress to[] = new InternetAddress[1];
to[0] = new
InternetAddress("[email protected]");
message.setRecipients(Message.RecipientType.TO, to);
message.setSubject("Session Demo 4");
message.setContent(content.toString(), "text/plain");
Transport.send(message);
System.out.println("Message Sent");
}
catch(Exception e)
{
System.out.println("Error Occured="+e);
e.printStackTrace();
}
String message = "<br><div style='text-align:center;'>"
+ "<h3>********** Hello World, Spring Mail
Tutorial</h3>This message is coming from HelloController.java
**********</div><br><br>";
return new ModelAndView("welcome", "message",
message);
}
}
<servlet>
<description></description>
<display-name>demo</display-name>
<servlet-name>demo</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</
servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>demo</servlet-name>
<url-pattern>/demo</url-pattern>
<url-pattern>/</url-pattern>
<url-pattern>/welcome.html</url-pattern>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
</web-app>
6. Inside Web-Inf create a folder named jsp and within this folder create a jsp file
named welcome.jsp as shown below:
<html>
<head>
<title>Reusing Email Session Demo
Example</title>
</head>
<body>${message}
</body>
</html>
7. Right Click Project “ResuingEmailSession”-> Run As-> Run On Sever
8. On Web Browser, type following URL:
http://localhost:9080/ReusingEmailSession/welcome
Sending Mail Using Velocity Mail Templates
<html>
<body>
Hello ${firstName} ${lastName},<p/>
Thanks
Support Team.
</body>
</html>
3. Create a package named spring inside src folder and create a java file
named applicationContext.xml file inside it.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-
context.xsd">
<bean id="velocityEngine"
class="org.springframework.ui.velocity.VelocityEngineFactoryBean"
>
<property name="velocityProperties">
<props>
<prop key="resource.loader">class</prop>
<prop
key="class.resource.loader.class">org.apache.velocity.runtime.res
ource.loader.ClasspathResourceLoader</prop>
</props>
</property>
</bean>
</beans>
4. Create a package named mailservice inside src and Create a java file
named EmailSender.java inside it.
package mailservice;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import
org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.stereotype.Component;
import org.springframework.ui.velocity.VelocityEngineUtils;
@Component("emailSender")
public class EmailSender {
@Autowired
private JavaMailSender mailSender;
@Autowired
private VelocityEngine velocityEngine;
public void sendEmail(final String toEmailAddresses, final String
fromEmailAddress,
final String subject) {
final Map<String, Object> input = new HashMap<String,
Object>();
input.put("firstName", "Mukesh");
input.put("lastName", "Regmi");
input.put("when", "06/21/2014");
final String body =
VelocityEngineUtils.mergeTemplateIntoString(velocityEngine,
"templates/reminder.vm", "UTF-8", input);
sendMessage(toEmailAddresses, fromEmailAddress, subject,
body);
}
public void sendSimpleEmail(final String toEmailAddresses, final
String fromEmailAddress,
final String subject) {
VelocityContext context = new VelocityContext();
context.put("firstName", "Mukesh");
context.put("lastName", "Regmi");
context.put("when", "06/21/2014");
Template t = velocityEngine.getTemplate(
"templates/reminder.vm" );
final StringWriter writer = new StringWriter();
t.merge(context, writer);
sendMessage(toEmailAddresses, fromEmailAddress, subject,
writer.toString());
}
private void sendMessage(final String toEmailAddresses, final
String fromEmailAddress,
final String subject, final String body){
package testpro;
import org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicationCont
ext;
import mailservice.EmailSender;
public class TestApp {
}
}
6. Right Click on VelocityDemo-> Run As-> Java Application
Note: If You get TLS Socket Conversion error, then it is better
recommended to disable Antivirus.
Reference:
1.http://asmitasapkota.blogspot.com/2013/06/velocity-template-with-spring.html
package mailservice;
import java.util.List;
import java.util.Map;
import org.springframework.mail.MailException;
package mailservice;
import java.io.File;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailException;
import org.springframework.mail.MailPreparationException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.springframework.ui.velocity.VelocityEngineUtils;
import org.springframework.core.io.FileSystemResource;
@Component("genericemailSender")
public class MailManagerImpl implements MailManager {
@Autowired
private JavaMailSender mailSender;
@Autowired
private VelocityEngine velocityEngine;
////////////////////////////////////////
MimeMessage message = mailSender.createMimeMessage();
// create the message using the specified template
MimeMessageHelper helper;
try
{
helper = new MimeMessageHelper(message, true, "UTF-8");
////////////////////////////////////////////////
// add the ‘from’ recipient(s) to the message
// add the sender to the message
helper.setFrom(senderAddress, senderName);
// add the ‘cc’ recipient(s) to the message
if(cc != null && !cc.isEmpty())
{
Iterator it = cc.keySet().iterator();
while(it.hasNext())
{
String name = (String) it.next();
String recipient = (String) cc.get(name);
helper.addCc(recipient, name);
}
}
// add the ‘bcc’ recipient(s) to the message
if(bcc != null && !bcc.isEmpty())
{
Iterator it = bcc.keySet().iterator();
while(it.hasNext())
{
String name = (String) it.next();
String recipient = (String) bcc.get(name);
helper.addBcc(recipient, name);
}
}
///////////////////////////////////////////////
if(to != null && !to.isEmpty())
{
Iterator it = to.keySet().iterator();
while(it.hasNext())
{
String name = (String) it.next();
String recipient = (String) to.get(name);
helper.addTo(recipient, name);
}
}
///////////message Body
final Map<String, Object> input = new HashMap<String,
Object>();
input.put("firstName", "Mukesh");
input.put("lastName", "Regmi");
input.put("when", "06/21/2014");
final String body =
VelocityEngineUtils.mergeTemplateIntoString(velocityEngine,
"templates/reminder.vm", "UTF-8", input);
helper.setSubject(subject);
helper.setText(body,true);
//Add Attachments
File attachs[] =new
File("D:/attachments").listFiles();
if(attachs != null)
{
for(int i=0;i<attachs.length;i++)
{
System.out.println(attachs[i]);
helper.addAttachment(attachs[i].getName(), new
FileSystemResource(attachs[i]));
}
}
mailSender.send(message);
System.out.println("Message Sent Successfully");
}
catch(Exception e)
{
System.out.println("Error="+e);
throw new MailPreparationException( "unable to
create the mime message helper", e);
}
///////////////////////////////////////////////Add
Attachments///////////////////////
}
3. Create a folder named attachments inside D drive and put files that you want to
send via attachments inside this folder.
package testpro;
import java.util.HashMap;
import java.util.Map;
import org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicationContext;
import mailservice.EmailSender;
import mailservice.MailManager;
import mailservice.MailManagerImpl;
public class TestAppGeneric {
public static void main(String[] args) {
ApplicationContext ctx = new
ClassPathXmlApplicationContext("spring/applicationContext.xml");
MailManager es = (MailManager)
ctx.getBean("genericemailSender");
final Map<String, String> to = new HashMap<String,
String>();
to.put("Mukesh Regmi", "[email protected]");
to.put("Makesh Regmi", "[email protected]");
////////////////////////////////////////////////////
final Map<String, String> cc = new HashMap<String, String>();
cc.put("Hari Pokharel", "[email protected]");
cc.put("Arjun Khadka", "[email protected]");
final Map<String, String> bcc = new HashMap<String,
String>();
bcc.put("Mike Regmi",
"[email protected]");
es.send("Mukesh Regmi", "[email protected]",to,
cc, bcc, "Spring-Email-Test-Ignore-this-Email");
// es.sendEmail("[email protected]",
"[email protected]","Hello Subject");
}
}