Sending simple and attach file using spring boot mail

Project Structure:

SpringSendMailApplication.java


package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringSendMailApplication {

	public static void main(String[] args) {
		SpringApplication.run(SpringSendMailApplication.class, args);

	}

}
    

SendController.java


package com.example.demo.controller;

import java.io.File;
import javax.mail.internet.MimeMessage;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
public class SendController {

	@Autowired
	private JavaMailSender javaMailSender;

	@PostMapping("/sendSimpleMail")
	public String sendSimpleMail(@RequestParam String receiver, @RequestParam String message,
			@RequestParam String subject) {

		SimpleMailMessage msg = new SimpleMailMessage();
		msg.setTo(receiver);

		msg.setSubject(subject);
		msg.setText(message);

		javaMailSender.send(msg);

		return "Send Message Successfully";
	}

	@PostMapping("/sendAttachMail")
	public String sendAttachMail(@RequestParam String sender, @RequestParam String receiver, @RequestParam String msg,
			@RequestParam String subject, MultipartFile file) throws Exception {

		MimeMessage message = javaMailSender.createMimeMessage();

		MimeMessageHelper helper = new MimeMessageHelper(message, true);

		helper.setFrom(sender);
		helper.setTo(receiver);
		helper.setSubject(subject);
		helper.setText(String.format(msg));

		File file1 = File.createTempFile("file", "." + file.getContentType().split("/")[1]);
		file.transferTo(file1);

		helper.addAttachment(file1.getName(), file1);

		javaMailSender.send(message);

		return "Send Message Successfully";
	}

}
    

application.properties

spring.mail.host=smtp.gmail.com
spring.mail.port=587
spring.mail.username=deep@gmail.com
spring.mail.password=############

spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.connectiontimeout=5000
spring.mail.properties.mail.smtp.timeout=5000
spring.mail.properties.mail.smtp.writetimeout=5000

spring.mail.properties.mail.smtp.starttls.enable=true
    

pom.xml

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
    

Output Screens:


No comments: