Sending email using velocity template


Email (electronic mail) is an effective medium to reach out to masses. In application, a need may arise to use email as mean of communicating with customers. A notification mail has to be send when someone post comment or transaction has been successfully completed etc.


A simple email service can be prepared within application with few steps. All we need is, mail sender service and a template.


Dependencies
commons-codec-1.6.jar
commons-collections-3.2.1.jar
commons-lang-2.5.jar
mail-1.4.4.jar
spring-context-support-3.2.2.RELEASE.jar
spring-core-3.2.3.RELEASE.jar
velocity-1.7.jar


Complete Code:

final String fromEmail = "from@gmail.com";
final String toEmail = "to@gmail.com";

	private JavaMailSender javaMailSender;

	public String templateSetup(Map<String, Object> properties, String templateName){
		final VelocityEngine velocityEngine = new VelocityEngine();
		velocityEngine.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
		velocityEngine.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
		velocityEngine.init();

		VelocityContext context = new VelocityContext();
		context.put("date", new Date());
		final Template template = velocityEngine.getTemplate(templateName);
		StringWriter writer = new StringWriter();
		template.merge(context, writer);

		return VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, template.getName(), "UTF-8", properties);
	}

	public JavaMailSender serverSetup(String password){
		JavaMailSenderImpl impl = new JavaMailSenderImpl();
		impl.setHost("smtp.gmail.com");
		impl.setPort(587);
		impl.setUsername("from@gmail.com");
		impl.setPassword(password);

		Properties mailProp = new Properties();
		mailProp.setProperty("mail.smtp.auth", "true");
		mailProp.setProperty("mail.smtp.starttls.enable", "true");

		impl.setJavaMailProperties(mailProp);

		javaMailSender = impl;
		return javaMailSender;
	}

	public void sendMail(String password, final String templateName, final String subject) throws Exception {

		final Map<String, Object> properties = new HashMap<String, Object>();
		properties.put("message", "Hello world!");

		MimeMessagePreparator p = new MimeMessagePreparator() {

			@Override
			public void prepare(MimeMessage mimeMessage) throws Exception {
				MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true);
				message.setTo(toEmail);
				message.setFrom(new InternetAddress(fromEmail));
				message.setSubject(subject);
				message.setText(templateSetup(properties, templateName), true);
			}
		};

		javaMailSender.send(p);
	}

	public static void main(String[] args) {
		MimeMailSender mail = new MimeMailSender();
		String password = "";
		try {
			System.out.print("Enter your password : ");

			BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
			password = br.readLine().trim();
			mail.serverSetup(password);
			br.close();

			mail.sendMail(password, "user.vm","This is test");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

Template : user.vm

<html>
<head>
</head>
<body>
    <div>${message}</div>
</body>
</html>


Leave a comment

Your email address will not be published. Required fields are marked *

 

This site uses Akismet to reduce spam. Learn how your comment data is processed.