Spring Boot Mail Templates
Spring Boot : Email (with AutoConfigure) *) We have already registered one Mail Account(Gmail.com) S#1 Goto Browser and Enter URL : www.gmail.com [Contact with Gmail Server] S#2 Fill details un/pwd for Login S#3 Click on compose button for new message creation S#4 Fill details (to,cc,bcc,subject,text, attachments..etc) S#5 Click on Send Button --------------------------------------------------------------- *) Java Mail Sender API(Sun/Oracle) used by Spring Boot with AutoConfig for implementing Email Application. in pom.xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency> *) MimeMessage : [MIME-Multipurpose Internet Mail Extension] It means, your email supports sending data like Image, Audio, Video, Pdf, Document, Text..etc. => Here, MIME indicates any MediaType. *) JavaMailSender (I) [org.springframework.mail.javamail] JavaMailSenderImpl(C) is impl class given by Spring F/w, which is Auto configured by Spring boot that helps us to Login With Mail Server. --------------------------------------------------------- Google Search: google gmail server smtp details host: smtp.gmail.com port: 587 (TLS) username: javaraghu2018@gmail.com password: 0044javaraghu2200 ---Spring Java Based configuration---- @Configuration public class AppConfig { @Bean public JavaMailSender jms() { JavaMailSenderImpl jm = new JavaMailSenderImpl(); jm.setHost("smtp.gmail.com"); jm.setPort(587); jm.setUsername("javaraghu2018@gmail.com"); jm.setPassword("0044javaraghu2200"); jm.setJavaMailProperties(props()->"tls->true"); return jm; } } ---------------------------------- *) Above code is automated and given in jar 'spring-boot-autoconfigure' class name : MailSenderPropertiesConfiguration. (ctrl+shift+T) *) But Above code is activated on few conditions. a. spring-boot-starter-mail added in pom.xml b. You must provide keys using prefix "spring.mail" c. You did not create this Bean manually like Spring code. ---application.properties---------------------------------- spring.mail.host=smtp.gmail.com spring.mail.port=587 spring.mail.username=javaraghu2018@gmail.com spring.mail.password=0044javaraghu2200 spring.mail.properties.mail.smtp.starttls.enable=true ---------------------------------------------------- ---application.yml---------------------------------- spring: mail: host: smtp.gmail.com password: 0044javaraghu2200 port: 587 username: javaraghu2018@gmail.com properties: mail: smtp: starttls: enable: true ---------------------- *) By using JavaMailSender(I) we can create one empty Message *) By using MimeMessageHelper(C) [org.springframework.mail.javamail] we can fill data *) By using JavaMailSender(I) we can send message. ---------------------------------------------------- Q) What is IOS N/w Layers Model Design? Q) Which Protocol is used for Emails? Q) How to add security to current protocol? Q) What is the difference b/w TLS, SSL? Q) What is CC and BCC and difference? A) Q) What is method overloading? A) ------------------------------------------------ =============code========================================= Name: SpringBoot2MailApp Dep : Java Mail Sender 1. application.yml spring: mail: host: smtp.gmail.com password: 0044javaraghu2200 port: 587 username: javaraghu2018@gmail.com properties: mail: smtp: starttls: enable: true 2. Service class package in.nareshit.raghu.service; import javax.mail.internet.MimeMessage; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.Resource; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.stereotype.Component; @Component public class MailService { @Autowired //Read new JavaMailSenderImpl() from container private JavaMailSender sender; public boolean sendEmail( String to, String cc[], String bcc[], String subject, String text, Resource file ) { boolean isSent = false; try { //create new MimeMessage MimeMessage message = sender.createMimeMessage(); // Use Helper class and fill details(to,cc..) //MimeMessageHelper helper = new MimeMessageHelper(message, file!=null?true:false); MimeMessageHelper helper = new MimeMessageHelper(message, file!=null); helper.setTo(to); if(cc!=null) helper.setCc(cc); if(bcc!=null) helper.setBcc(bcc); helper.setSubject(subject); helper.setText(text); if(file!=null) { //file name, file data helper.addAttachment(file.getFilename(), file); } //send message sender.send(message); isSent=true; } catch (Exception e) { isSent=false; e.printStackTrace(); } return isSent; } } 3. Runner class package in.nareshit.raghu.runner; import java.util.Date; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.core.io.FileSystemResource; import org.springframework.core.io.Resource; import org.springframework.stereotype.Component; import in.nareshit.raghu.service.MailService; @Component public class MailServiceRunner implements CommandLineRunner{ @Autowired private MailService ms; public void run(String... args) throws Exception { Resource file = new FileSystemResource("F:\\Images\\SpringBoot8PM_22022021.png"); boolean sent = ms.sendEmail( "javaraghu2018@gmail.com", new String[] { "chsprakash86@gmail.com", "amritagrawal255@gmail.com", "ambikareddy7198@gmail.com", "umangsontakke70@gmail.com" }, new String[] { "mahanandananda2017@gmail.com", "nageswarik997@gmail.com", "yerane21@gmail.com", "prasanta.sahoo@irisbusiness.com", "anjaliguptajnp21@gmail.com" }, "Welcome to MySubject", "Hello Data!" + new Date(), file); if(sent) System.out.println("MAIL SENT"); else System.out.println("NOT SENT"); } } ------------------------------------------------------------ Q) Are yu going to send email everytime with attachment or without attachment? A) It may be with attachment/ with out with attachment. file!=null? then allocate attachment memory : else no. *) file!=null?true:false If file exist then allocate attchment memory else not. 1) a>b?tue:false is equal to below (in short format) 2) a>b
*) MiemMessage : MIME- Multipurpose Internet Mail Extension [Any type of data..] *) MimeMessageHelper : Supports filling data in Message object (to,subj,text,att...) *) This object takes two inputs "message:MimeMessage,multipart:boolean" *) If you attachments to pass using email then define multipart=true, else define multipart=false. *) To create one empty message use JavaMailSender MimeMessage message = sender.createMimeMessage(); *) even to submit/send message use JavaMailSender sender.send(message); ------------------------------------------------------------- *) In Helper class we have setText() overloaded methods setText(String text); //calling setText(text,false) internally. setText(String text, boolean html); *) If first method is called then data is sent as plain text (Display what it is). 2nd method convert data into HTML Format and gives output in HTML Output(like browser output). ---------------------------------------------------------- Q) What is Template Email? A) Define one HTML Format commonly for multiple users. and replace their data at runtime and send to them using HTML Format --core java code-- package in.nareshit.raghu; import java.io.FileInputStream; public class MailTemplate { private static String template =null; static { try { FileInputStream fis = new FileInputStream("F:\\Notes\\mailtemplate.txt"); byte[] bytes= new byte[fis.available()]; fis.read(bytes); template = new String(bytes); } catch (Exception e) { e.printStackTrace(); } } public static String getTemplate() { return template; } public static void main(String[] args) { String template = getTemplate(); template=template.replace("{{user}}", "AJAY") .replace("{{firstname}}", "SENTIL") .replace("{{lastname}}", "AJAY KUMAR") .replace("{{date}}", new java.util.Date().toString()); System.out.println(template); } } ---mailtemplate.txt--- <html> <body> <h1>WELCOME TO {{user}} </h1> This is sample mail to Mr/Mrs/Ms. {{firstname}} - {{lastname}} <br/> <b>Thank you very much.</b> Date : {{date}} </body> </html> ----------------------- Q) Read File Data into one String variable? FileInputStream fis = new FileInputStream("F:\\Notes\\mailtemplate.txt"); byte[] bytes= new byte[fis.available()]; fis.read(bytes); template = new String(bytes); Q) Replace Sting data with other String input? template.replace(toBereplaced, replaceText) Q) What is method overloading? same method name with different parameters. =======================code========================== Name :SpringBoot2Email Dep : Java Mail Sender 1. application.yml spring: mail: host: smtp.gmail.com password: 0044javaraghu2200 port: 587 username: javaraghu2018@gmail.com properties: mail: smtp: starttls: enable: true 2. MailTemplate package in.nareshit.raghu; import java.io.FileInputStream; public class MailTemplate { private static String template =null; static { try { FileInputStream fis = new FileInputStream("F:\\Notes\\mailtemplate.txt"); byte[] bytes= new byte[fis.available()]; fis.read(bytes); template = new String(bytes); } catch (Exception e) { e.printStackTrace(); } } private static String getTemplate() { return template; } public static String getTemplateData( String user,String fn,String ln) { String template = getTemplate(); template=template.replace("{{user}}", user) .replace("{{firstname}}", fn) .replace("{{lastname}}", ln) .replace("{{date}}", new java.util.Date().toString()); return template; } } 3. MailService package in.nareshit.raghu.service; import javax.mail.internet.MimeMessage; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.Resource; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.stereotype.Component; @Component public class MailService { @Autowired //Read new JavaMailSenderImpl() from container private JavaMailSender sender; public boolean sendEmail( String to, String cc[], String bcc[], String subject, String text, Resource file ) { boolean isSent = false; try { //create new MimeMessage MimeMessage message = sender.createMimeMessage(); // Use Helper class and fill details(to,cc..) //MimeMessageHelper helper = new MimeMessageHelper(message, file!=null?true:false); MimeMessageHelper helper = new MimeMessageHelper(message, file!=null); helper.setTo(to); if(cc!=null) helper.setCc(cc); if(bcc!=null) helper.setBcc(bcc); helper.setSubject(subject); helper.setText(text,true); //helper.setText(text);//false if(file!=null) { //file name, file data helper.addAttachment(file.getFilename(), file); } //send message sender.send(message); isSent=true; } catch (Exception e) { isSent=false; e.printStackTrace(); } return isSent; } public boolean sendEmail( String to, String subject, String text) { return sendEmail(to, null, null, subject, text, null); } } 4. Test Runner package in.nareshit.raghu.runner; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.core.io.FileSystemResource; import org.springframework.core.io.Resource; import org.springframework.stereotype.Component; import in.nareshit.raghu.MailTemplate; import in.nareshit.raghu.service.MailService; @Component public class MailServiceRunner implements CommandLineRunner{ @Autowired private MailService ms; public void run(String... args) throws Exception { Resource file = new FileSystemResource("F:\\Images\\SpringBoot8PM_22022021.png"); /* boolean sent = ms.sendEmail( "javaraghu2018@gmail.com", null, null, "Welcome to MySubject", MailTemplate.getTemplateData( "KUMAR", "Rank. Jayrai", " RAJU"), file); */ boolean sent = ms.sendEmail("javaraghu2018@gmail.com", "Welcome to MySubject", MailTemplate.getTemplateData( "SAMUL", "St. Annos", " Phillips ") ); if(sent) System.out.println("MAIL SENT"); else System.out.println("NOT SENT"); } } ===================================================================== *)Note : Email sending failed. a. Invalid Un/password (or with spaces in yml/props files) b. Purchased Service from Google else enable less secure apps > Click on Top right corner on email account (profile picture) > Manage your google account > Security > Less Secure Apps > Turn on Less secure apps. c. Disable Antivirus for few minutes. d. 2 step verification must be disabled. e.*** System JDK/JRE, OS is effected with virus. *) Google Search: google email domain purchase -----------------------------------------------------------------
No Comments Yet!!