0% found this document useful (0 votes)
14 views

Mail

Uploaded by

Surendra
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Mail

Uploaded by

Surendra
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 25

Sending Mail and attachment using Standalone Client

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">

<context:component-scan base-package="mailservice" />

<!-- SET default mail properties -->


<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.transport.protocol">smtp</prop>
<prop key="mail.smtp.auth">true</prop>
<prop key="mail.smtp.starttls.enable">true</prop>
<prop key="mail.debug">true</prop>
</props>
</property>
</bean>

<!-- 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;

public class TestApp {

public static void main(String[] args) {


//Create the application context
ApplicationContext context = new
FileSystemXmlApplicationContext("mail-context.xml");

//Get the mailer instance


MySimpleMailService mailer = (MySimpleMailService)
context.getBean("mailService");

//Send a composed mail


mailer.sendMail("[email protected]", "Test Subject",
"Testing body");

//Send a pre-configured mail


mailer.sendPreConfiguredMail("Exception occurred everywhere..
where are you ????");

5. Logon to gmail-> Click on My Account-> Click on Sign-In and Security-> Scroll At


the bottom-> Make sure “Allow less Secure Apps” option is on.
6. Right Click on TestApp.java-Run As-> Java Application
Sending Attachment
We will use above project to send attachment as well.
1. Create a Java file named MyAttachmentMailService.java inside mailservice
package

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;

public class MyAttachmentMailService {


private JavaMailSender mailSender;
private SimpleMailMessage simpleMailMessage;
public void setSimpleMailMessage(SimpleMailMessage
simpleMailMessage) {
this.simpleMailMessage = simpleMailMessage;
}

public void setMailSender(JavaMailSender mailSender) {


this.mailSender = mailSender;
}
public void sendMail(String dear, String content) {

MimeMessage message = mailSender.createMimeMessage();

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));

FileSystemResource file = new FileSystemResource("C:\\


dell\\log.txt");
helper.addAttachment(file.getFilename(), file);
}catch (MessagingException e) {
throw new MailParseException(e);
}
mailSender.send(message);
System.out.println("Email Sent Successfully..");
}
}

2. Create an XML file named attachment-context.xml inside src package


<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.xsd">

<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="mailMail" class="mailservice.MyAttachmentMailService">


<property name="mailSender" ref="mailSender" />
<property name="simpleMailMessage" ref="customeMailMessage" />
</bean>

<bean id="customeMailMessage"
class="org.springframework.mail.SimpleMailMessage">

<property name="from" value="[email protected]" />


<property name="to" value="[email protected]" />
<property name="subject" value="Testing Subject 6" />
<property name="text">
<value>
<![CDATA[
Dear %s,
Mail Content : %s
]]>
</value>
</property>
</bean>
</beans>
3. Create a log.txt file inside c:\dell folder. We are going to send this file as an
attachment
4. Create a Java file named TestAppAttachment.java inside testpro package

package testpro;

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

import mailservice.MyAttachmentMailService;

public class TestAppAttachment {

public static void main(String[] args) {


ApplicationContext context =
new ClassPathXmlApplicationContext("attachment-
context.xml");

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);
}
});

MimeMessage message = new MimeMessage(session);


message.setFrom(new
InternetAddress(username,"ekataBookStore.com"));

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");

2. Right Click on JavaEESessionDemo.java->Run As-> Java Application


Reusing an Exisitng Mail Session.
If we are running email sending application inside a container that already provides a
mail session, then instead of creating the new session, the session from application
context will be retrieved and re-used.
If Tomcat exposes the JavaMail Session through JNDI under the JNDI name
mail/SessionChanged, then our application program will retrieve this session and use it
for sending email.
Let us define JNDI resource in server.xml and context.xml as shown below[ Expand the
Servers and you will see below directory structure]:

In server.xml, locate the <GlobalNamingResources></GlobalNamingResources> tag


and within this tag, add following code:
<Resource name="mail/SessionChanged" auth="Container"
type="javax.mail.Session"
username="[email protected]"
pwd="#yourgmailpassword"
mail.debug="true"
mail.transport.protocol="smtp"
mail.smtp.host= "smtp.gmail.com"
mail.smtp.auth= "true"
mail.smtp.port= "587"
mail.smtp.starttls.enable="true"
description="Global E-Mail Resource"
/>
</context>

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

1. Create a Dynamic Web Project named ReusingEmailSession, convert it into


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>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>

2. Create a package named mycontroller inside src and create HelloController.java


class within it as shown below:

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);
}
}

3. Add a Dispatcher Servlet named demo to this project.


4. Inside WebContent/Web-INF folder, create dispatcher servlet application context
file named demo-servlet.xml as following:
<?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"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xsi:schemaLocation="http://www.springframework.org/schema/jdbc
http://www.springframework.org/schema/jdbc/spring-jdbc-4.2.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<context:component-scan base-package="mycontroller">
</context:component-scan>
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>

5. Your web.xml file should contain following code:


<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID"
version="2.5">
<display-name>ReusingEmailSession</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>

<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

Velocity templates allows to send a standard email template messages to


recipient.

1. Create a Java Project named VelocityMailDemo, convert it into 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>VelocityMailDemo</groupId>
<artifactId>VelocityMailDemo</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-context</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity</artifactId>
<version>1.7</version>
</dependency>
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.5</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 templates and create a template file named


reminder.vm inside it.

<html>
<body>
Hello ${firstName} ${lastName},<p/>

This is a reminder email. Please remember to submit your


application by EOD ${when}.<p/>

Thanks

Support Team.

</body>
</html>

Note that EmailSender.java uses this velocity template to send email

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">

<context:component-scan base-package="mailservice" />


<bean id="mailSender"
class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="javaMailProperties">
<props>
<prop key="mail.smtp.auth">true</prop>
<prop key="mail.smtp.starttls.enable">true</prop>
<prop key="mail.smtp.host">smtp.gmail.com</prop>
<prop key="mail.smtp.port">587</prop>
</props>
</property>
<property name="username" value="[email protected]" />
<property name="password" value="manishaluvsmukesh" />
</bean>

<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){

MimeMessagePreparator preparator = new


MimeMessagePreparator() {
public void prepare(MimeMessage mimeMessage) throws
Exception {

MimeMessageHelper message = new


MimeMessageHelper(mimeMessage, true);
message.setTo(toEmailAddresses);
message.setFrom(new
InternetAddress(fromEmailAddress));
message.setSubject(subject);
message.setText(body, true);
}
};
this.mailSender.send(preparator);
System.out.println("Message Sent Successfully..");
}
}

5. Create a package named testpro and create a file named TestApp.java


inside it.

package testpro;
import org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicationCont
ext;
import mailservice.EmailSender;
public class TestApp {

public static void main(String[] args) {


ApplicationContext ctx = new
ClassPathXmlApplicationContext("spring/applicationContext.xml");
EmailSender es = (EmailSender)
ctx.getBean("emailSender");
es.sendEmail("[email protected]",
"[email protected]","Hello Subject");
//es.sendSimpleEmail("[email protected]",
"[email protected]","Hello");

}
}
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

Generic Mail Manager


Generic Mail Manager will send same email message based on velocity template to
multiple recipients, multiple ccs, bccs. Moreover, all files located at the specified folder
will be sent as an Attachment. In our program, all files located at D:\attachments folder
will be sent as an attachment to these tos, ccs, and bccs user.
We will use the same VelocityMailDemo project to create Generic Mail Manager as
following:
1. Create an interface file named MailManager inside “mailservice” package.

package mailservice;

import java.util.List;
import java.util.Map;

import org.springframework.mail.MailException;

public interface MailManager


{
public void send(String senderName, String senderAddress, Map
to, Map cc, Map bcc, String subject) throws MailException ;
}

2. Create a file named MailManagerImpl that implements MailManager interface


inside “mailservice” package.

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;

public void send(String senderName, String senderAddress, Map to,


Map cc, Map bcc, String subject) throws MailException
{

////////////////////////////////////////
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.

4. Create TestAppGeneric.java inside testpro

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");

}
}

5. Right Click TestAppGeneric-> Run As-> Java Application


Note: You are going to use the same applicationContext.xml file inside spring
folder for this project as well.

You might also like