Skip to content

Instantly share code, notes, and snippets.

@zubayerahamed
Last active August 6, 2019 11:22
Show Gist options
  • Save zubayerahamed/5678a44a3870b50282b3b7f1a9343526 to your computer and use it in GitHub Desktop.
Save zubayerahamed/5678a44a3870b50282b3b7f1a9343526 to your computer and use it in GitHub Desktop.
Send email using velocity template and attach a file
server.port=8080
server.error.whitelabel.enabled=false
spring.thymeleaf.cache=false
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8"/>
<title>Insert title here</title>
</head>
<body>
<span th:if="${sm}" th:text="${sm}"></span>
<a th:unless="${sm}" th:href="@{/mail}">Send Mail</a>
</body>
</html>
<html>
<head>
<title></title>
</head>
<body>
This is a test mail body Mr. <b>${fname} ${lname}</b>.<br/>
You may put HTML/text content here.
<br/>
<br/>
With best wishes,<br/>
${proprietor}
</body>
</html>
mail.smtp.starttls.enable=true
mail.smtp.host=smtp.gmail.com
mail.smtp.port=587
mail.smtp.auth=true
[email protected]
mail.passwd=your_password
package com.coderslab.controller;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
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.core.env.Environment;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
@Controller
@RequestMapping("/")
public class MailController {
@Autowired
Environment env;
@GetMapping
public String loadMainPage(Model model) {
return "index";
}
@GetMapping("/mail")
public String sendMail(RedirectAttributes redirect)
throws AddressException, MessagingException, FileNotFoundException, IOException {
String to = "[email protected]";
String from = "[email protected]";
Properties props = System.getProperties();
props.load(new FileInputStream(new File("src/main/resources/mail-settings.properties")));
Session session = Session.getDefaultInstance(props, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(props.getProperty("mail.user"), props.getProperty("mail.passwd"));
}
});
// Creating default MIME message object
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject("Test mail through simple java API");
BodyPart body = new MimeBodyPart();
// velocity stuff.
// Initialize velocity
VelocityEngine ve = new VelocityEngine();
ve.init();
// get the template
Template t = ve.getTemplate("src/main/resources/static/mail-body-template.vm");
// create context and add data
VelocityContext context = new VelocityContext();
context.put("fname", "Zubayer");
context.put("lname", "Ahamed");
context.put("proprietor", "coderslab.com");
/* now render the template into a StringWriter */
StringWriter out = new StringWriter();
t.merge(context, out);
// velocity stuff end
body.setContent(out.toString(), "text/html");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(body);
body = new MimeBodyPart();
String filename = "src/main/resources/static/mail-attachment-template.csv";
DataSource source = new FileDataSource(filename);
body.setDataHandler(new DataHandler(source));
body.setFileName("attachment.csv");
multipart.addBodyPart(body);
message.setContent(multipart);
// send mail
Transport.send(message);
redirect.addFlashAttribute("sm", "Email send successfull");
return "redirect:/";
}
}
package com.coderslab;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MailVelocityApplication {
public static void main(String[] args) {
SpringApplication.run(MailVelocityApplication.class, args);
}
}
<?xml version="1.0" encoding="UTF-8"?>
<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>com.coderslab</groupId>
<artifactId>mail-velocity</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>mail-velocity</name>
<description>Sending mail usign velocity tempalte</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.10.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web-services</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity</artifactId>
<version>1.7</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
@zubayerahamed
Copy link
Author

zubayerahamed commented Feb 20, 2018

Project Structure in STS ide
selection_003

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment