Skip to content

Commit 761eaad

Browse files
committed
20210903 增加spring javamail 最佳实践
1 parent c0a5b63 commit 761eaad

File tree

12 files changed

+749
-0
lines changed

12 files changed

+749
-0
lines changed

README.md

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,8 @@
2929

3030
- [FreeMarker 快速入门](https://www.cnblogs.com/itdragon/p/7750903.html)
3131

32+
- [邮件实现详解(四)------JavaMail 发送(带图片和附件)和接收邮件](https://www.cnblogs.com/ysocean/p/7666061.html)
33+
3234

3335

3436
## 项目3:poi-practice
@@ -41,6 +43,18 @@
4143

4244

4345

46+
## 项目4:spring-javamail-practice
47+
48+
### 参考文档
49+
50+
- [使用Spring JavaMailSender发送邮件](https://www.jianshu.com/p/ef7c24dde787)
51+
52+
53+
54+
55+
56+
57+
4458
## TODO
4559

4660
- Swagger

images/mailwithpicture.jpg

398 KB
Loading
Lines changed: 136 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,136 @@
1+
package com.coderdream;
2+
3+
/**
4+
* @author :CoderDream
5+
* @date :Created in 2021/9/3 14:37
6+
* @description:
7+
* @modified By:CoderDream
8+
* @version: $
9+
*/
10+
import java.util.Date;
11+
import java.util.Properties;
12+
13+
import javax.activation.DataHandler;
14+
import javax.activation.FileDataSource;
15+
import javax.mail.Message;
16+
import javax.mail.MessagingException;
17+
import javax.mail.Session;
18+
import javax.mail.Transport;
19+
import javax.mail.internet.AddressException;
20+
import javax.mail.internet.InternetAddress;
21+
import javax.mail.internet.MimeBodyPart;
22+
import javax.mail.internet.MimeMessage;
23+
import javax.mail.internet.MimeMultipart;
24+
import javax.mail.internet.MimeUtility;
25+
26+
public class SendMailText_Picture_Enclosure {
27+
//发件人地址
28+
public static String senderAddress = "acoder@126.com";
29+
//收件人地址
30+
public static String recipientAddress = "xulin.wh@qq.com";
31+
//发件人账户名
32+
public static String senderAccount = "acoder";
33+
//发件人账户密码
34+
public static String senderPassword = "XPMVBOLNQCXWQMRA";
35+
36+
public static void main(String[] args) throws Exception {
37+
//1、连接邮件服务器的参数配置
38+
Properties props = new Properties();
39+
//设置用户的认证方式
40+
props.setProperty("mail.smtp.auth", "true");
41+
//设置传输协议
42+
props.setProperty("mail.transport.protocol", "smtp");
43+
//设置发件人的SMTP服务器地址
44+
props.setProperty("mail.smtp.host", "smtp.126.com");
45+
//2、创建定义整个应用程序所需的环境信息的 Session 对象
46+
Session session = Session.getInstance(props);
47+
//设置调试信息在控制台打印出来
48+
session.setDebug(true);
49+
//3、创建邮件的实例对象
50+
Message msg = getMimeMessage(session);
51+
//4、根据session对象获取邮件传输对象Transport
52+
Transport transport = session.getTransport();
53+
//设置发件人的账户名和密码
54+
transport.connect(senderAccount, senderPassword);
55+
//发送邮件,并发送到所有收件人地址,message.getAllRecipients() 获取到的是在创建邮件对象时添加的所有收件人, 抄送人, 密送人
56+
transport.sendMessage(msg,msg.getAllRecipients());
57+
58+
//5、关闭邮件连接
59+
transport.close();
60+
}
61+
62+
/**
63+
* 获得创建一封邮件的实例对象
64+
* @param session
65+
* @return
66+
* @throws MessagingException
67+
* @throws AddressException
68+
*/
69+
public static MimeMessage getMimeMessage(Session session) throws Exception{
70+
//1.创建一封邮件的实例对象
71+
MimeMessage msg = new MimeMessage(session);
72+
//2.设置发件人地址
73+
msg.setFrom(new InternetAddress(senderAddress));
74+
/**
75+
* 3.设置收件人地址(可以增加多个收件人、抄送、密送),即下面这一行代码书写多行
76+
* MimeMessage.RecipientType.TO:发送
77+
* MimeMessage.RecipientType.CC:抄送
78+
* MimeMessage.RecipientType.BCC:密送
79+
*/
80+
msg.setRecipient(MimeMessage.RecipientType.TO,new InternetAddress(recipientAddress));
81+
//4.设置邮件主题
82+
msg.setSubject("邮件主题(包含图片和附件)","UTF-8");
83+
84+
//下面是设置邮件正文
85+
//msg.setContent("简单的纯文本邮件!", "text/html;charset=UTF-8");
86+
87+
// 5. 创建图片"节点"
88+
MimeBodyPart image = new MimeBodyPart();
89+
// 读取本地文件
90+
DataHandler dh = new DataHandler(new FileDataSource("D:\\DailyReport\\202108.jpg"));
91+
// 将图片数据添加到"节点"
92+
image.setDataHandler(dh);
93+
// 为"节点"设置一个唯一编号(在文本"节点"将引用该ID)
94+
image.setContentID("mailTestPic");
95+
96+
// 6. 创建文本"节点"
97+
MimeBodyPart text = new MimeBodyPart();
98+
// 这里添加图片的方式是将整个图片包含到邮件内容中, 实际上也可以以 http 链接的形式添加网络图片
99+
text.setContent("这是一张图片<br/><a href='http://www.cnblogs.com/ysocean/p/7666061.html'><img src='cid:mailTestPic'/></a>", "text/html;charset=UTF-8");
100+
101+
// 7. (文本+图片)设置 文本 和 图片"节点"的关系(将 文本 和 图片"节点"合成一个混合"节点")
102+
MimeMultipart mm_text_image = new MimeMultipart();
103+
mm_text_image.addBodyPart(text);
104+
mm_text_image.addBodyPart(image);
105+
mm_text_image.setSubType("related"); // 关联关系
106+
107+
// 8. 将 文本+图片 的混合"节点"封装成一个普通"节点"
108+
// 最终添加到邮件的 Content 是由多个 BodyPart 组成的 Multipart, 所以我们需要的是 BodyPart,
109+
// 上面的 mailTestPic 并非 BodyPart, 所有要把 mm_text_image 封装成一个 BodyPart
110+
MimeBodyPart text_image = new MimeBodyPart();
111+
text_image.setContent(mm_text_image);
112+
113+
// 9. 创建附件"节点"
114+
MimeBodyPart attachment = new MimeBodyPart();
115+
// 读取本地文件
116+
DataHandler dh2 = new DataHandler(new FileDataSource("D:\\DailyReport\\202108.docx"));
117+
// 将附件数据添加到"节点"
118+
attachment.setDataHandler(dh2);
119+
// 设置附件的文件名(需要编码)
120+
attachment.setFileName(MimeUtility.encodeText(dh2.getName()));
121+
122+
// 10. 设置(文本+图片)和 附件 的关系(合成一个大的混合"节点" / Multipart )
123+
MimeMultipart mm = new MimeMultipart();
124+
mm.addBodyPart(text_image);
125+
mm.addBodyPart(attachment); // 如果有多个附件,可以创建多个多次添加
126+
mm.setSubType("mixed"); // 混合关系
127+
128+
// 11. 设置整个邮件的关系(将最终的混合"节点"作为邮件的内容添加到邮件对象)
129+
msg.setContent(mm);
130+
//设置邮件的发送时间,默认立即发送
131+
msg.setSentDate(new Date());
132+
133+
return msg;
134+
}
135+
136+
}

pom.xml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
<module>junit5-practice</module>
1313
<module>javamail-practice</module>
1414
<module>poi-practice</module>
15+
<module>spring-javamail-practice</module>
1516
</modules>
1617

1718
<name>Maven</name>

spring-javamail-practice/pom.xml

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
3+
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4+
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
5+
<modelVersion>4.0.0</modelVersion>
6+
7+
<groupId>com.coderdream</groupId>
8+
<artifactId>spring-javamail-practice</artifactId>
9+
<version>1.0-SNAPSHOT</version>
10+
11+
<name>spring-javamail-practice</name>
12+
<!-- FIXME change it to the project's website -->
13+
<url>http://www.example.com</url>
14+
15+
<properties>
16+
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
17+
<maven.compiler.source>1.8</maven.compiler.source>
18+
<maven.compiler.target>1.8</maven.compiler.target>
19+
</properties>
20+
21+
<dependencies>
22+
23+
<dependency>
24+
<groupId>org.springframework</groupId>
25+
<artifactId>spring-context-support</artifactId>
26+
<version>5.3.9</version>
27+
</dependency>
28+
29+
<dependency>
30+
<groupId>junit</groupId>
31+
<artifactId>junit</artifactId>
32+
<version>4.11</version>
33+
<scope>test</scope>
34+
</dependency>
35+
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
36+
<dependency>
37+
<groupId>org.projectlombok</groupId>
38+
<artifactId>lombok</artifactId>
39+
<version>1.18.20</version>
40+
<scope>provided</scope>
41+
</dependency>
42+
<dependency>
43+
<groupId>javax.mail</groupId>
44+
<artifactId>mail</artifactId>
45+
<version>1.4.7</version>
46+
<scope>compile</scope>
47+
</dependency>
48+
</dependencies>
49+
50+
<build>
51+
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
52+
53+
</pluginManagement>
54+
</build>
55+
</project>
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
package com.coderdream;
2+
3+
/**
4+
* Hello world!
5+
*
6+
*/
7+
public class App
8+
{
9+
public static void main( String[] args )
10+
{
11+
System.out.println( "Hello World!" );
12+
}
13+
}
Lines changed: 124 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,124 @@
1+
package com.coderdream;
2+
3+
import org.springframework.mail.javamail.JavaMailSender;
4+
import org.springframework.mail.javamail.JavaMailSenderImpl;
5+
6+
import java.io.IOException;
7+
import java.io.InputStream;
8+
import java.util.Properties;
9+
10+
/**
11+
* @author :CoderDream
12+
* @date :Created in 2021/9/3 16:36
13+
* @description:
14+
* @modified By:CoderDream
15+
* @version: $
16+
*/
17+
public class InitJavaMailSender {
18+
/**
19+
* 此类的作用是加载配置文件来创建JavaMailSender对象 JavaMailSenderImpl是该接口的实现类
20+
* 因此我们需要对JavaMailSenderImpl进行配置 在spring的环境下 我们可以使用加载配置文件的方式 或者
21+
* 在spring配置文件中直接配置该bean(由spring托管)使用时@Autowired直接注入即可
22+
* <bean id="javaMailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
23+
* <property name="host" value="${mail.smtp.host}" />
24+
* <property name="username" value="${mail.smtp.username}" />
25+
* <property name="password" value="${mail.smtp.password}" />
26+
* <property name="defaultEncoding" value="${mail.smtp.defaultEncoding}" />
27+
* <property name="javaMailProperties">
28+
* <props>
29+
* <prop key="mail.smtp.auth">${mail.smtp.auth}</prop>
30+
* <prop key="mail.smtp.timeout">${mail.smtp.timeout}</prop>
31+
* ...
32+
* </props>
33+
* </property>
34+
* </bean>
35+
* 本次采用加载配置文件的方式
36+
* 由spring提供 其底层使用的仍然是javax.mail进行邮件的发送
37+
* JavaMailSenderImpl 依赖javax.mail 和 spring-context-support包
38+
*/
39+
// 传输协议
40+
private static String protocol;
41+
// 服务器主机名
42+
private static String host;
43+
// 服务器端口号
44+
private static String port;
45+
// 是否进行用户名密码校验
46+
private static String auth;
47+
// 设置是否使用ssl安全连接
48+
private static String enableSSL;
49+
// 设置是否显示debug信息
50+
private static String debug;
51+
// 超时时间
52+
private static String timeout;
53+
// 编码格式
54+
private static String defaultEncoding;
55+
// 邮箱地址
56+
public static String username;
57+
// 授权码
58+
private static String password;
59+
60+
private static volatile JavaMailSenderImpl javaMailSenderImpl;
61+
62+
static {
63+
init();
64+
}
65+
66+
private static void init() {
67+
// 加载配置文件
68+
Properties properties = new Properties();
69+
InputStream resourceAsStream = JavaMailSender.class.getClassLoader().getResourceAsStream("mail.properties");
70+
try {
71+
properties.load(resourceAsStream);
72+
protocol = properties.getProperty("mail.transport.protocol");
73+
host = properties.getProperty("mail.smtp.host");
74+
port = properties.getProperty("mail.smtp.port");
75+
auth = properties.getProperty("mail.smtp.auth");
76+
enableSSL = properties.getProperty("mail.smtp.ssl.enable");
77+
debug = properties.getProperty("mail.debug");
78+
timeout = properties.getProperty("mail.smtp.timeout");
79+
defaultEncoding = properties.getProperty("mail.smtp.defaultEncoding");
80+
username = properties.getProperty("mail.smtp.username");
81+
password = properties.getProperty("mail.smtp.password");
82+
System.out.println("mail.properties加载成功");
83+
} catch (IOException e) {
84+
e.printStackTrace();
85+
System.out.println("mail.properties加载失败");
86+
} finally {
87+
if (null != resourceAsStream) {
88+
try {
89+
resourceAsStream.close();
90+
} catch (IOException e) {
91+
e.printStackTrace();
92+
}
93+
}
94+
}
95+
}
96+
97+
/**
98+
* 使用单例获取JavaMailSender 双重检查既保证的线程安全 又保证了效率 又能起到延迟加载的作用
99+
* @return
100+
*/
101+
public static JavaMailSender getJavaMailSender() {
102+
if (null == javaMailSenderImpl) {
103+
synchronized (InitJavaMailSender.class) {
104+
if (null == javaMailSenderImpl) {
105+
javaMailSenderImpl = new JavaMailSenderImpl();
106+
javaMailSenderImpl.setProtocol(protocol);
107+
javaMailSenderImpl.setHost(host);
108+
javaMailSenderImpl.setPort(Integer.parseInt(port));
109+
javaMailSenderImpl.setDefaultEncoding(defaultEncoding);
110+
javaMailSenderImpl.setUsername(username);
111+
javaMailSenderImpl.setPassword(password);
112+
Properties properties = new Properties();
113+
properties.setProperty("mail.smtp.auth", auth);
114+
properties.setProperty("mail.smtp.ssl.enable", enableSSL);
115+
properties.setProperty("mail.debug", debug);
116+
properties.setProperty("mail.smtp.timeout", timeout);
117+
javaMailSenderImpl.setJavaMailProperties(properties);
118+
}
119+
}
120+
}
121+
return javaMailSenderImpl;
122+
}
123+
124+
}

0 commit comments

Comments
 (0)