最近项目中需要发送邮件的功能,于是百度一大把例子。但是有很多都是一样的,一点特点都没有。所以决定整理一番。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
<!-- 配置MailSender -->
<
bean
id
=
"mailSender"
class
=
"org.springframework.mail.javamail.JavaMailSenderImpl"
>
<!-- 邮件服务器 -->
<
property
name
=
"host"
value
=
"smtp.163.com"
/>
<!-- 端口 -->
<
property
name
=
"port"
value
=
"25"
/>
<!-- 你的邮箱 -->
<
property
name
=
"username"
value
=
""
/>
<!-- 邮箱密码 -->
<
property
name
=
"password"
value
=
""
/>
<
property
name
=
"javaMailProperties"
>
<
props
>
<!-- 是否进行身份认证 -->
<
prop
key
=
"mail.smtp.auth"
>true</
prop
>
<!-- 是否采用SSL登录 -->
<
prop
key
=
"mail.smtp.starttls.enable"
>true</
prop
>
</
props
>
</
property
>
</
bean
>
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
public
static
void
simpleMail() {
try
{
// 使用Spring提供的MailSender
ApplicationContext app =
new
ClassPathXmlApplicationContext(
"spring-mail.xml"
);
JavaMailSender mailSender = (JavaMailSender) app
.getBean(
"mailSender"
);
// 创建一个纯文本邮件
SimpleMailMessage mail =
new
SimpleMailMessage();
// 发送方
mail.setFrom(YourMail);
// 接收人
mail.setTo(ToMail);
// 邮件标题
mail.setSubject(
"测试简单邮件发送"
);
// 内容
mail.setText(
"测试使用SpringMailSender发送邮件"
);
// 发送
mailSender.send(mail);
System.out.println(
"邮件发送成功!"
);
}
catch
(Exception e) {
e.printStackTrace();
}
}
|
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
|
public
static
void
attachedFileMail() {
try
{
ApplicationContext app =
new
ClassPathXmlApplicationContext(
"spring-mail.xml"
);
JavaMailSender mailSender = (JavaMailSender) app
.getBean(
"mailSender"
);
MimeMessage mime = mailSender.createMimeMessage();
// multipart模式 为true时发送附件 可以设置html格式
MimeMessageHelper messageHelper =
new
MimeMessageHelper(mime,
true
,
"utf-8"
);
// 发送方
messageHelper.setFrom(YourMail);
// 接收人
messageHelper.setTo(ToMail);
// 邮件标题
messageHelper.setSubject(
"测试包含附件邮件发送"
);
// true 表示启动HTML格式的邮件
messageHelper
.setText(
"<html><head></head><body><h3>你好:附件中有惊喜,请查收!</h3></body></html>"
,
true
);
// 附件
FileSystemResource file =
new
FileSystemResource(
new
File(
"D:\\a.xls"
));
messageHelper.addAttachment(
"a.xls"
, file);
// 发送
mailSender.send(mime);
System.out.println(
"邮件发送成功!"
);
}
catch
(MessagingException e) {
e.printStackTrace();
}
}
|