preface

This article mainly introduces the SpringBoot project to achieve file upload and mail sending functions.

The SpringBoot file is uploaded

Note: If you want to get the project directly, you can jump to the bottom and download the project code through the link.

The development of preparation

Environmental requirements

The JDK: 1.8

SpringBoot: 1.5.9. RELEASE

First, there are Maven dependencies:

The pom.xml file is as follows:

< properties > < project. Build. SourceEncoding > utf-8 < / project. Build. SourceEncoding > < Java version > 1.8 < / Java version > Piler < maven.com. Source > 1.8 < / maven.com piler. Source > < maven.com piler. Target > 1.8 < / maven.com piler. Target > < / properties > <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.9.RELEASE</version> <relativePath /> </parent> <dependencies> <! <dependency> <groupId>org.springframework. Boot </groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <! --> <dependency> <groupId>org.springframework. Boot </groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <! <dependency> <groupId>org.springframework. Boot </groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> </dependencies>Copy the code

Then there is the file configuration for application.properties.

application.properties:

banner.charset=UTF-8
server.tomcat.uri-encoding=UTF-8
spring.http.encoding.charset=UTF-8
spring.http.encoding.enabled=true
spring.http.encoding.force=true
spring.messages.encoding=UTF-8
server.port=8182

spring.http.multipart.maxFileSize=100Mb
spring.http.multipart.maxRequestSize=100Mb

filePath=F:/test/
Copy the code

. Note: the spring, the HTTP multipart maxFileSize and spring. HTTP multipart. MaxRequestSize is set the upload file size, I set here is 100 MB, filePath is the path of the file upload, Since I am using Windows, set the path to F:/test/.

The code

SpringBoot itself is very friendly to file uploads. Just use the MultipartFile class as a parameter in the control layer and accept file uploads. It is up to us to decide how to handle the uploaded files.

First let’s write a front-end interface and add a button for uploading files. Since SpringBoot is very friendly with Thymeleaf support, we will write a simple interface for uploading files directly using Thymeleaf.

The HTML code is as follows:

<! DOCTYPE html> <html> <head> <title>uploading.html</title> <meta name="keywords" content="keyword1,keyword2,keyword3"></meta>
    <meta name="description" content="this is my page"></meta>
    <meta name="content-type" content="text/html; charset=UTF-8"></meta>

  </head>

  <body>
  <form enctype="multipart/form-data" method="post" action="/uploading">
    <input type="file" name="file"/>
    <input type="submit" value="Upload"/>
    </form>
  </body>
</html>


Copy the code

Note: If you don’t want to write a front-end interface, you can use tools like Postman. Postman operates as follows:

Fill in the URL path, choose Post -> Body – Select form-data format -> Key – select File type, select file, and click Send to upload the file.

Since we only do file uploads, we don’t do any other business logic processing, so we only implement it in the control layer. Define an interface to upload files and use the MultipartFile class to receive them.

The code is as follows:


@Controller
public class FileUploadController {
	
	@Value("${filePath}")
	private String filePath;
	
    @GetMapping("/upload")
    public String uploading() {// jump to the clones.html in the templates directoryreturn "uploading"; } // Handle file uploads @postmapping ("/uploading")
    public @ResponseBody String uploading(@RequestParam("file") MultipartFile file,
            HttpServletRequest request) {
        try {
            uploadFile(file.getBytes(), filePath, file.getOriginalFilename());
        } catch (Exception e) {
        	e.printStackTrace();
        	System.out.println("File upload failed!");
        	return "uploading failure";
        }
        System.out.println("File uploaded successfully!");
        return "uploading success";
    }
    
    
    
    public void  uploadFile(byte[] file, String filePath, String fileName) throws Exception { 
        File targetFile = new File(filePath);  
        if(!targetFile.exists()){    
            targetFile.mkdirs();    
        }       
        FileOutputStream out = new FileOutputStream(filePath+fileName);
        out.write(file);
        out.flush();
        out.close();
    }
    
}
	
Copy the code

Note: the above code is only an example, the actual situation please pay attention to the exception handling! The above stream closure should have been in finally, but it was actually written for convenience.

App entrance

Basically the same as a normal SpringBoot project.

The code is as follows:


@SpringBootApplication
public class FileUploadApplication {

    public static void main(String[] args)  {
        SpringApplication.run(FileUploadApplication.class, args);
        System.out.println("FileUploadApplication started successfully!"); }}Copy the code

A functional test

After we successfully started the program, enter in the browser: http://localhost:8182/upload, then select a file to upload, we finally to F: / test/path to check whether have the file.

Here’s an example:

Example diagram uploaded using Postman:

As a final note, if the file is uploaded repeatedly, the later file will replace the previous one.

SpringBoot email is sent

Note: If you want to get the project directly, you can jump to the bottom and download the project code through the link.

The development of preparation

Environmental requirements

The JDK: 1.8

SpringBoot: 1.5.9. RELEASE

First, there are Maven dependencies:

The pom.xml file is as follows:

< properties > < project. Build. SourceEncoding > utf-8 < / project. Build. SourceEncoding > < Java version > 1.8 < / Java version > Piler < maven.com. Source > 1.8 < / maven.com piler. Source > < maven.com piler. Target > 1.8 < / maven.com piler. Target > < / properties > <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.9.RELEASE</version> <relativePath /> </parent> <dependencies> <! <dependency> <groupId>org.springframework. Boot </groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <! --> <dependency> <groupId>org.springframework. Boot </groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <! <dependency> <groupId>org.springframework. Boot </groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency> <dependency>  <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> </dependency> </dependencies>Copy the code

Then there is the file configuration of application.properties, which we need to fill in according to our actual situation. As shown in the following configuration file example, individuals use QQ email, so spring.mail.host is configured to smtp.qq.com. In the following example, you only need to enter your personal email account and password. If error 535 occurs, the POP3/SMTP service must be enabled on the email box and the password must be replaced by the authorization code.

application.properties:

server.port = 8182
spring.mail.host=smtp.qq.com
[email protected]
spring.mail.password=xxx
spring.mail.default-encoding=UTF-8
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
Copy the code

The code

SpringBoot has integrated the function of sending mail. After we introduce the relevant rack package, we only need to use the Send method in the JavaMailSender class to complete the sending of mail. If you also want to mail static resources and attachments, the methods in the JavaMailSender class will do the same. If you want to send custom template content, you need to use the methods in the TemplateEngine class.

When we use email, these four things are most important: the sender, the recipient, the sending subject, and the message to send. Therefore, we can create a simple mail entity class according to these four types, which is convenient for relevant business processing.

Entity class code

The code is as follows:

Public class Mail {/** sender */ private String sender; /** receiver/private String receiver; /** subject */ private String subject; /** Send message */ private String text; // getters and setters omitted}Copy the code

Here we still define the interface to send the mail. When we send the mail, we still only need to know the sender, recipient, sending subject and sending message, and the rest can be completed in the code. Here we simply define a few interfaces to achieve the above requirements

Control layer code:

The code is as follows:


@RestController
@RequestMapping("/api/mail") public class MailController { private static Logger LOG=LoggerFactory.getLogger(MailController.class); @Autowired private JavaMailSender mailSender; @Autowired private TemplateEngine templateEngine; /* * Send regular email */ @postMapping ("/sendMail")
    public String sendMail(@RequestBody Mail mail) {
    	SimpleMailMessage message = new SimpleMailMessage();
		message.setFrom(mail.getSender());
		message.setTo(mail.getReceiver());
		message.setSubject(mail.getSubject());
		message.setText(mail.getText());
		mailSender.send(message);
		LOG.info("Sent successfully!");
        return "Sent successfully!"; } /* * Send attachments */ @postMapping ("/sendAttachments")
    public String sendAttachmentsMail(@RequestBody Mail mail) throws MessagingException  {

    	MimeMessage mimeMessage = mailSender.createMimeMessage();
    	MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
    	helper.setFrom(mail.getSender());
    	helper.setTo(mail.getReceiver());
    	helper.setSubject(mail.getSubject());
    	helper.setText(mail.getText());
    	FileSystemResource file = new FileSystemResource(new File("1.png"));
    	helper.addAttachment("The attachment JPG"., file);
    	mailSender.send(mimeMessage);
		return "Sent successfully!"; } /* * Send file */ @postmapping ("/sendInlineMail")
    public String sendInlineMail(@RequestBody Mail mail) throws Exception {

    	MimeMessage mimeMessage = mailSender.createMimeMessage();

    	MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true); helper.setFrom(mail.getSender()); helper.setTo(mail.getReceiver()); helper.setSubject(mail.getSubject()); // Text is HTML helper.settext (mail.gettext (),true);
    	FileSystemResource file = new FileSystemResource(new File("1.png"));
    	helper.addInline("File", file);
    	mailSender.send(mimeMessage);
    	return "Sent successfully!"; } /* * Send template */ @postmapping ("/sendTemplateMail")
    public void sendTemplateMail(@RequestBody Mail mail) throws Exception {

    	MimeMessage mimeMessage = mailSender.createMimeMessage();

    	MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true); helper.setFrom(mail.getSender()); helper.setTo(mail.getReceiver()); helper.setSubject(mail.getSubject()); Context = new Context(); context.setVariable("id"."1");
        context.setVariable("name"."xuwujing");
        String emailContent = templateEngine.process("emailTemplate", context);
    	helper.setText(emailContent, true); mailSender.send(mimeMessage); }}Copy the code

App entrance

Basically the same as a normal SpringBoot project.

The code is as follows:


@SpringBootApplication
public class MailApp 
{
    public static void main( String[] args )
    {
		SpringApplication.run(MailApp.class, args);
		System.out.println("MailApp started successfully!"); }}Copy the code

A functional test

After we successfully launched the program, we tested it using the Postman tool.

POST is used to make requests

POST http://localhost:8182/api/mail/sendMail

The Body argument is:

{” sender “:” [email protected] “, “receiver” : “[email protected]”, “subject” : “test subject”, “text” : “test message”}

Note: of course the parameters here fill in your own email can!

The return parameter is:

Sent successfully!

Figure:

Some students may not know how to generate the authorization code, here I use QQ mailbox to generate the authorization code of an example diagram to illustrate.

Figure:

other

SpringBoot project to achieve file upload and email function of the article explained here, if there is something wrong, welcome to correct!

The project address

SpringBoot implementation file upload project address: github.com/xuwujing/sp…

SpringBoot email delivery project address: github.com/xuwujing/sp…

SpringBoot entire collection address: github.com/xuwujing/sp…

SpringBoot integration series of articles

  • SpringBoot configuration file reading and use of filters and interceptors

  • SpringBoot Restful service

  • SpringBoot+Mybatis+ Druid+PageHelper implements multiple data sources and paging

  • SpringBoot is compatible with ElasticSearch

  • SpringBoot integrates Kafka with Storm

  • SpringBoot integrates Jsp with Thymeleaf

  • SpringBoot integrates Netty and uses Protobuf for data transfer

  • SpringBoot is simply packaged and deployed

  • SpringBoot integration Redis uses Restful style to implement CRUD functionality

  • SpringBoot elegant global exception handling

Music to recommend

Recommend a piece of pure music to read in quiet down!

Original is not easy, if you feel good, I hope to give a recommendation! Your support is the biggest motivation for my writing! Copyright: www.cnblogs.com/xuwujing CSDN blog.csdn.net/qazwsxpcm Personal blog: www.panchengming.com