這篇文章介紹springboot的郵件傳送。
由於很簡單就沒有分出server和imp之類,只是在controller簡單寫個方法進行測試。
首先pom檔案加入spring-boot-starter-mail,程式碼如下:
<?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.dalaoyang</groupId>
<artifactId>springboot_mail</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>springboot_mail</name>
<description>springboot_mail</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</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-mail</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
複製程式碼
接下來是application.properties,裡面包含傳送郵箱的地址,賬號密碼,接信地址,由於只是測試,所以都是固定寫死的,如果專案中需要,可以根據自行情況進行修改。
##埠號
server.port=8888
##這裡根據自己的情況填寫
##郵箱伺服器地址
##QQ smtp.qq.com
##sina smtp.sina.cn
##aliyun smtp.aliyun.com
##163 smtp.163.com
spring.mail.host=smtp.aliyun.com
##郵箱使用者名稱
spring.mail.username=dalaoyang@aliyun.com
##郵箱密碼(注意:qq郵箱應該使用獨立密碼,去qq郵箱設定裡面獲取)
spring.mail.password=******
##編碼格式
spring.mail.default-encoding=UTF-8
##傳送郵件地址
mail.fromMail.sender=dalaoyang@aliyun.com
##接收郵件地址
mail.fromMail.receiver=yangyang@dalaoyang.cn
複製程式碼
然後先展示一下controller的完整程式碼:
package com.dalaoyang.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
/**
* @author dalaoyang
* @Description
* @project springboot_learn
* @package com.dalaoyang.controller
* @email yangyang@dalaoyang.cn
* @date 2018/4/10
*/
@RestController
public class MailController {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Value("${mail.fromMail.sender}")
private String sender;
@Value("${mail.fromMail.receiver}")
private String receiver;
@Autowired
private JavaMailSender javaMailSender;
/* *
* @Description http://localhost:8888/sendMail
* @author dalaoyang
* @email 397600342@qq.com
* @method 傳送文字郵件
* @date
* @param
* @return
*/
@RequestMapping("/sendMail")
public String sendMail() {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(sender);
message.setTo(receiver);
message.setSubject("大老楊");
message.setText("你好你好你好!");
try {
javaMailSender.send(message);
logger.info("簡單郵件已經傳送。");
} catch (Exception e) {
logger.error("傳送簡單郵件時發生異常!", e);
}
return "success";
}
/* *
* @Description http://localhost:8888/sendHtmlMail
* @author dalaoyang
* @email 397600342@qq.com
* @method 傳送html郵件
* @date
* @param
* @return
*/
@RequestMapping("/sendHtmlMail")
public String testHtmlMail() {
String content="<html>\n" +
"<body>\n" +
" <h3>hello world ! 這是一封Html郵件!</h3>\n" +
"</body>\n" +
"</html>";
MimeMessage message = javaMailSender.createMimeMessage();
try {
//true表示需要建立一個multipart message
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(sender);
helper.setTo(receiver);
helper.setSubject("html mail");
helper.setText(content, true);
javaMailSender.send(message);
logger.info("html郵件傳送成功");
} catch (MessagingException e) {
logger.error("傳送html郵件時發生異常!", e);
}
return "success";
}
/* *
* @Description http://localhost:8888/sendFilesMail
* @author dalaoyang
* @email 397600342@qq.com
* @method 傳送附件郵件
* @date
* @param
* @return
*/
@RequestMapping("/sendFilesMail")
public String sendFilesMail() {
String filePath="/Users/dalaoyang/Downloads/article_tag.sql";
MimeMessage message = javaMailSender.createMimeMessage();
try {
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(sender);
helper.setTo(receiver);
helper.setSubject("附件郵件");
helper.setText("這是一封帶附件的郵件", true);
FileSystemResource file = new FileSystemResource(new File(filePath));
String fileName = filePath.substring(filePath.lastIndexOf(File.separator));
helper.addAttachment(fileName, file);
javaMailSender.send(message);
logger.info("帶附件的郵件已經傳送。");
} catch (MessagingException e) {
logger.error("傳送帶附件的郵件時發生異常!", e);
}
return "success";
}
/* *
* @Description http://localhost:8888/sendInlineResourceMail
* @author dalaoyang
* @email 397600342@qq.com
* @method 傳送圖片郵件
* @date
* @param
* @return
*/
@RequestMapping("/sendInlineResourceMail")
public String sendInlineResourceMail() {
String Id = "dalaoyang12138";
String content="<html><body>這是有圖片的郵件:<img src=\'cid:" + Id + "\' ></body></html>";
String imgPath = "/Users/dalaoyang/Downloads/dalaoyang.jpeg";
MimeMessage message = javaMailSender.createMimeMessage();
try {
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(sender);
helper.setTo(receiver);
helper.setSubject("這是有圖片的郵件");
helper.setText(content, true);
FileSystemResource res = new FileSystemResource(new File(imgPath));
helper.addInline(Id, res);
javaMailSender.send(message);
logger.info("嵌入靜態資源的郵件已經傳送。");
} catch (MessagingException e) {
logger.error("傳送嵌入靜態資源的郵件時發生異常!", e);
}
return "success";
}
}
複製程式碼
然後一點一點來,本文分4種情況: 1.傳送簡單的文字郵件
/* *
* @Description http://localhost:8888/sendMail
* @author dalaoyang
* @email yangyang@dalaoyang.cn
* @method 傳送文字郵件
* @date
* @param
* @return
*/
@RequestMapping("/sendMail")
public String sendMail() {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(sender);
message.setTo(receiver);
message.setSubject("大老楊");
message.setText("你好你好你好!");
try {
javaMailSender.send(message);
logger.info("簡單郵件已經傳送。");
} catch (Exception e) {
logger.error("傳送簡單郵件時發生異常!", e);
}
return "success";
}
複製程式碼
訪問http://localhost:8888/sendMail,可以看到頁面上顯示success,在去看郵箱可以看到如下圖,證明傳送成功
2.傳送html郵件
/* *
* @Description http://localhost:8888/sendHtmlMail
* @author dalaoyang
* @email yangyang@dalaoyang.cn
* @method 傳送html郵件
* @date
* @param
* @return
*/
@RequestMapping("/sendHtmlMail")
public String testHtmlMail() {
String content="<html>\n" +
"<body>\n" +
" <h3>hello world ! 這是一封Html郵件!</h3>\n" +
"</body>\n" +
"</html>";
MimeMessage message = javaMailSender.createMimeMessage();
try {
//true表示需要建立一個multipart message
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(sender);
helper.setTo(receiver);
helper.setSubject("html mail");
helper.setText(content, true);
javaMailSender.send(message);
logger.info("html郵件傳送成功");
} catch (MessagingException e) {
logger.error("傳送html郵件時發生異常!", e);
}
return "success";
}
複製程式碼
訪問http://localhost:8888/sendHtmlMail,可以看到頁面上顯示success,在去看郵箱可以看到如下圖,證明傳送成功
3.傳送附件郵件
/* *
* @Description http://localhost:8888/sendFilesMail
* @author dalaoyang
* @email yangyang@dalaoyang.cn
* @method 傳送附件郵件
* @date
* @param
* @return
*/
@RequestMapping("/sendFilesMail")
public String sendFilesMail() {
String filePath="/Users/dalaoyang/Downloads/article_tag.sql";
MimeMessage message = javaMailSender.createMimeMessage();
try {
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(sender);
helper.setTo(receiver);
helper.setSubject("附件郵件");
helper.setText("這是一封帶附件的郵件", true);
FileSystemResource file = new FileSystemResource(new File(filePath));
String fileName = filePath.substring(filePath.lastIndexOf(File.separator));
helper.addAttachment(fileName, file);
javaMailSender.send(message);
logger.info("帶附件的郵件已經傳送。");
} catch (MessagingException e) {
logger.error("傳送帶附件的郵件時發生異常!", e);
}
return "success";
}
複製程式碼
訪問http://localhost:8888/sendFilesMail,可以看到頁面上顯示success,在去看郵箱可以看到如下圖,證明傳送成功
4.傳送圖片郵件
/* *
* @Description http://localhost:8888/sendInlineResourceMail
* @author dalaoyang
* @email yangyang@dalaoyang.cn
* @method 傳送圖片郵件
* @date
* @param
* @return
*/
@RequestMapping("/sendInlineResourceMail")
public String sendInlineResourceMail() {
String Id = "dalaoyang12138";
String content="<html><body>這是有圖片的郵件:<img src=\'cid:" + Id + "\' ></body></html>";
String imgPath = "/Users/dalaoyang/Downloads/dalaoyang.jpeg";
MimeMessage message = javaMailSender.createMimeMessage();
try {
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(sender);
helper.setTo(receiver);
helper.setSubject("這是有圖片的郵件");
helper.setText(content, true);
FileSystemResource res = new FileSystemResource(new File(imgPath));
helper.addInline(Id, res);
javaMailSender.send(message);
logger.info("嵌入靜態資源的郵件已經傳送。");
} catch (MessagingException e) {
logger.error("傳送嵌入靜態資源的郵件時發生異常!", e);
}
return "success";
}
複製程式碼
訪問http://localhost:8888/sendInlineResourceMail,可以看到頁面上顯示success,在去看郵箱可以看到如下圖,證明傳送成功