springboot整合mail郵箱傳送
阿新 • • 發佈:2018-11-10
springboot整合mail郵箱傳送
1.專案框架結構圖
2.pom.xml
<?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.wpf</groupId> <artifactId>springboot_email</artifactId> <version>1.0-SNAPSHOT</version> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.1.RELEASE</version> </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-freemarker</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency> </dependencies> </project>
2.application.yml
server:
port: 8080
spring:
freemarker:
suffix: .html
cache: false
template-loader-path: classpath:/templates
mail:
host: smtp.163.com
username: #用來發送的郵箱賬號
password: #郵箱密碼
3.1個實體類,email
package com.wpf.pojo; public class Email { //接收者郵箱 private String email; //郵件主題 private String title; //郵件內容 private String context; public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getContext() { return context; } public void setContext(String context) { this.context = context; } }
4.controller 核心程式碼
@Controller public class EamilController { @Autowired private JavaMailSender javaMailSender; //從配置檔案中獲取登入的郵箱賬號作為傳送者郵箱 @Value("${spring.mail.username}") private String FromEmail; @RequestMapping("/sendEmail") @ResponseBody public String sendEmail(Email email){ SimpleMailMessage message = new SimpleMailMessage(); //建立一封郵件 message.setFrom(FromEmail); //傳送者郵箱 message.setTo(email.getEmail()); //接收者郵箱 message.setSubject(email.getTitle()); //郵件的標題 message.setText(email.getContext()); //郵件內容 javaMailSender.send(message); //傳送 return "傳送成功!"; } //進入index頁面 @RequestMapping("/index.html") public String index(){ return "index"; } }
5.基本web測試頁面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="/sendEmail" method="post">
接收郵箱:<input type="text" name="email"><br>
標題:<input type="text" name="title"><br>
內容:<textarea name="context" id="" cols="30" rows="10"></textarea><br>
<input type="submit" value="傳送">
</form>
</body>
</html>
專案原始碼:https://download.csdn.net/download/weixin_42460179/10729181