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

Spring Boot Email

Uploaded by

mouneshgs96
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Spring Boot Email

Uploaded by

mouneshgs96
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

Mr.

RAGHU

SPRING BOOT MAIL API


Spring Email API has been created by Spring Framework using java-mail API
and POJI-POJO Design Pattern.

Spring Email API is a simplified email service which can be implemented and
integrated with any spring application easily.

By using Java mail API (given by Sun Microsystem) coding and setup is lengthy,
it is simplified with POJI-POJO given below:

Spring Email API supports MIME Type Email Sending (Multipurpose Internet
Mail Extension). It means “Any kind of file as attachment”,
EX: Video, Audio, Text, Document, Images etc…
I.e shown as :

Page 1 of 9
Mr. RAGHU

Spring Email API also provided one Helper class “MIMEMessageHelper” to


create message (writing code) in less lines of code.

To provide attachment details use MultiPartFile Concept SystemResource.


(EX: FileSystemResource or use Resource generic interface).

Page 2 of 9
Mr. RAGHU

pom.xml:

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
Page 3 of 9
Mr. RAGHU

</dependency>

MailSender class:

package com.app.raghu.service;

import javax.mail.internet.MimeMessage;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
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 AppMailSender {

@Autowired
private JavaMailSender mailsender;

@Value("${spring.mail.username}")
private String from;

public boolean sendEmail(


String to,
String sub,
String text,
Resource file)
{
boolean status = false;
try {
// 1. Create Message Object
MimeMessage message = mailsender.createMimeMessage();

// 2. Create helper class Object

Page 4 of 9
Mr. RAGHU

MimeMessageHelper helper = new


MimeMessageHelper(message, file != null ? true : false);

// 3. Compose Message
helper.setTo(to);
helper.setFrom("[email protected]");
helper.setSubject(sub);
helper.setText(text);
helper.addAttachment(file.getFilename(), file);

// 4. Send Email
mailsender.send(message);
status = true;
} catch (Exception e) {
status = false;
e.printStackTrace();
}
return status;
}
}

Test class:
package com.app.raghu.test;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.io.UrlResource;
import org.springframework.stereotype.Component;

import com.app.raghu.service.AppMailSender;

@Component
public class TestMail implements CommandLineRunner {

@Autowired

Page 5 of 9
Mr. RAGHU

private AppMailSender es;

public void run(String... args) throws Exception {


//FileSystemResource file = new FileSystemResource("D:\\ GitHub.png");
UrlResource file = new
UrlResource("https://img.freepik.com/premium-vector/cartoon-cute-young-
doctor-waving_70172-2682.jpg");
es.sendEmail("[email protected]", "Hello", "Welcome", file);
}

application.properties
spring.mail.host=smtp.gmail.com
spring.mail.port=587
spring.mail.username=********@gmail.com
spring.mail.password=************
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true

*) We cannot use Gmail Account password for sending emails. We must


generate App Password for that Enable 2-Step Verification in your Gmail
account and generate app password using below link.
https://myaccount.google.com/apppasswords

Live class code:


package com.app.raghu.service;

import javax.mail.internet.MimeMessage;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
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 AppMailSender {

Page 6 of 9
Mr. RAGHU

@Autowired
private JavaMailSender sender;

@Value("${spring.mail.username}")
private String from;

public boolean sendEmail(


String to,
String cc[],
String bcc[],
String subject,
String text,
Resource files[])
{

boolean sent = false;

//1. Create Empty Email object


MimeMessage message = sender.createMimeMessage();

try {
//2. Fill details
//here 2nd params indicates attachment exist or not?
MimeMessageHelper helper = new
MimeMessageHelper(message, files!=null && files.length>0);

helper.setTo(to);
if(cc!=null)
helper.setCc(cc);
if(bcc!=null)
helper.setBcc(bcc);

helper.setFrom(from);

helper.setSubject(subject);
//helper.setText(text);
helper.setText(text,true);

//filename, file data


if(files!=null && files.length>0) {
for(Resource file : files)
helper.addAttachment(file.getFilename(),
file);
}

//3. Click on send Button


sender.send(message);
sent = true;
} catch (Exception e) {

Page 7 of 9
Mr. RAGHU

e.printStackTrace();
}

return sent;
}
}

Test class:
package com.app.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.core.io.UrlResource;
import org.springframework.stereotype.Component;

import com.app.raghu.service.AppMailSender;

@Component
public class TestEmailRunner implements CommandLineRunner {

@Autowired
private AppMailSender sender;

public void run(String... args) throws Exception {

FileSystemResource file1 = new FileSystemResource("D:\\


Notes\\doctor.png");
UrlResource file2 = new
UrlResource("https://img.jagranjosh.com/imported/images/E/GK/sachin-
records.png");

boolean sent = sender.sendEmail(


"[email protected]", //to
new String[] { //cc
"[email protected]",
"[email protected]"
},
new String[] {//bcc
"[email protected]",
"[email protected]",
"[email protected]"
},
"God Of Cricket", //subject
//text
"<html> <body> <h1>Master Blaster!!</h1>
<p>Great Batsman!!</p> </body></html>",
new Resource[] { //files

Page 8 of 9
Mr. RAGHU

file1,file2
});

if(sent)
System.out.println("EMAIL IS SENT");
else
System.out.println("SENDING FAILED");
}

Page 9 of 9

You might also like