JavaMail整合Gmail邮箱服务器

igxiaoshan Lv5

JavaMail整合Gmail邮箱服务器

在Spring Boot项目中整合JavaMail服务

集成JavaMail

1.添加依赖

pom.xml中添加Spring Boot Starter Mail依赖

1
2
3
4
5
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>

2.配置邮件服务

application.propertiesapplication.yml文件中添加邮件服务器配置

1
2
3
4
5
6
7
8
9
10
11
12
13
spring:
mail:
host: smtp.example.com
port: 587
username: your_email@example.com
password: your_password
properties:
mail:
smtp:
auth: true
starttls:
enable: true

3.创建邮件服务类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

@Service
public class EmailService {

@Autowired
private JavaMailSender mailSender;

public void sendSimpleEmail(String to, String subject, String text) {
SimpleMailMessage message = new SimpleMailMessage();
message.setTo(to);
message.setSubject(subject);
message.setText(text);
mailSender.send(message);
}
}

4.使用邮件服务

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class EmailController {

@Autowired
private EmailService emailService;

@GetMapping("/send-email")
public String sendEmail(@RequestParam String to, @RequestParam String subject, @RequestParam String text) {
emailService.sendSimpleEmail(to, subject, text);
return "Email sent successfully";
}
}

5.测试类

1
http://localhost:8080/send-email?to=recipient@example.com&subject=Test&text=Hello

6.扩展html发送邮件或者发送附件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.springframework.mail.javamail.MimeMessageHelper;

public void sendHtmlEmail(String to, String subject, String htmlContent) throws MessagingException {
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, "utf-8");
helper.setText(htmlContent, true);
helper.setTo(to);
helper.setSubject(subject);
mailSender.send(mimeMessage);
}

public void sendEmailWithAttachment(String to, String subject, String text, String pathToAttachment) throws MessagingException {
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(text);
FileSystemResource file = new FileSystemResource(new File(pathToAttachment));
helper.addAttachment("Invoice", file);
mailSender.send(mimeMessage);
}

使用JavaMail整合Gmail

使用IMAP服务

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
spring:
receiver:
mail:
host: imap.gmail.com
port: 993
username: your_email@gmail.com
password: app_secret # 需要单独开通
protocol: imap
ssl:
enable: true
properties:
mail:
imap:
ssl:
enable: true
trust: imap.gmail.com
connectiontimeout: 300000 # 连接超时五分钟
timeout: 300000 # 读超时五分钟
writetimeout: 300000 # 写超时五分钟
store:
protocol: imap

监听Gmail邮箱邮件通知

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
package com.cmiot.onepark.email;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.mail.*;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.search.FlagTerm;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Properties;

@Service
public class Receiver {

@Autowired
private GmailProperties gmailProperties;

@Scheduled(fixedRate = 60000)
public void receiveEmails() throws NoSuchProviderException, InterruptedException {

try {
URL url = new URL("https://api.ipify.org?format=json");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
// 打印响应
int responseCode = connection.getResponseCode();
System.out.println("Response Code: " + responseCode);
try (BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
String inputLine;
StringBuilder content = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
System.out.println("Response: " + content.toString());
}
} catch (Exception e) {
e.printStackTrace();
}


System.out.println("-------------运行监听任务---------------------------------------------");

Properties props = new Properties();
props.put("mail.imap.ssl.enable", "true");
props.put("mail.imap.host", gmailProperties.getHost());
props.put("mail.imap.port", gmailProperties.getPort());
props.put("mail.imap.connectiontimeout", "300000"); // 连接超时五分钟
props.put("mail.imap.timeout", "300000"); // 读超时五分钟
props.put("mail.imap.writetimeout", "300000"); // 写超时五分钟

props.put("mail.smtp.auth", "true");
String user = gmailProperties.getUsername().split("@")[0];
props.put("mail.imap.user", user);
Session session = Session.getInstance(props, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
System.out.println("PasswordAuthentication user: " + gmailProperties.getUsername());
System.out.println("PasswordAuthentication password: " + gmailProperties.getPassword());
return new PasswordAuthentication(gmailProperties.getUsername(), gmailProperties.getPassword());
}
});

session.setDebug(true);
try (Store store = session.getStore("imap")) {
System.out.println("Full URL: " + store.getURLName().toString());
System.out.println("Host: " + store.getURLName().getHost());
System.out.println("Username: " + store.getURLName().getUsername());

store.connect("imap.gmail.com", gmailProperties.getUsername(), gmailProperties.getPassword());
Folder inbox = store.getFolder("INBOX");
inbox.open(Folder.READ_ONLY);
inbox.open(Folder.READ_WRITE); // 需要读写权限才能标记邮件为已读
// 搜索未读邮件
FlagTerm unseenFlagTerm = new FlagTerm(new Flags(Flags.Flag.SEEN), false);
Message[] messages = inbox.search(unseenFlagTerm);
System.out.println("收件箱的邮件数:" + messages.length);

for (Message message : messages) {
if (message instanceof MimeMessage) {
MimeMessage mimeMessage = (MimeMessage) message;
System.out.println("----------------------------------------------------------");
System.out.println("Subject: " + mimeMessage.getSubject());
System.out.println("From ToString: " + mimeMessage.getFrom()[0].toString());
System.out.println("From: " + mimeMessage.getFrom()[0]);
System.out.println("Content: " + getTextFromMessage(mimeMessage));
System.out.println("----------------------------------------------------------");

// 标记邮件为已读
message.setFlag(Flags.Flag.SEEN, true);
}
}
} catch (MessagingException e) {
throw new RuntimeException(e);
} catch (Exception e) {
throw new RuntimeException(e);
}

}

private static String getTextFromMessage(Message message) throws Exception {
String result = "";
if (message.isMimeType("text/plain")) {
result = message.getContent().toString();
} else if (message.isMimeType("multipart/*")) {
MimeMultipart mimeMultipart = (MimeMultipart) message.getContent();
result = getTextFromMimeMultipart(mimeMultipart);
}
return result;
}

private static String getTextFromMimeMultipart(MimeMultipart mimeMultipart) throws Exception {
StringBuilder result = new StringBuilder();
int count = mimeMultipart.getCount();
for (int i = 0; i < count; i++) {
BodyPart bodyPart = mimeMultipart.getBodyPart(i);
if (bodyPart.isMimeType("text/plain")) {
result.append(bodyPart.getContent());
} else if (bodyPart.isMimeType("text/html")) {
String html = (String) bodyPart.getContent();
result.append(org.jsoup.Jsoup.parse(html).text());
} else if (bodyPart.getContent() instanceof MimeMultipart) {
result.append(getTextFromMimeMultipart((MimeMultipart) bodyPart.getContent()));
}
}
return result.toString();
}
}

Gmail账号配置

开通两步验证

GMail谷歌邮箱《两步验证》是谷歌邮箱的安全机制,会让你的邮箱安全性更高。

GMail邮箱添加《应用专用密码》

https://security.google.com/settings/security/apppasswords?pli=1

应用专用密码请求链接生成,共16个字母,4个一组,在这里要记下这个专用密码(使用的时候要注意,要去掉中间的空格,密码只显示一次)