avatar

Java发送邮件

Java 发送邮件

本节作为对菜鸟教程-SendMail的补充。

开始需要下载相应的Jar包,并添加到ClassPath,发送邮箱选择的是自己的Gmail邮箱(推荐),接收邮箱是网易邮箱(任意),SMTP协议选择的端口是Port:465(推荐,一般会默认Port:25,但是容易报MessagingException)。如果使用Gmail作为发送邮箱的话,会发现使用谷歌账户的密码依然会出AuthenticationFailedException异常,因为google开启了两步验证功能,所以如果要使用javamail发送邮件的话,需要一个应用专用密码(app password),这样即使密码被盗取也无法登录到账号。这里是谷歌官方提供的方法- 应用专用密码

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
// 文件名 SendEmail.java

import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;

public class SendEmail
{
public static void main(String [] args)
{
final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";

// 发件人电子邮箱
String from = "YourGmail@gmail.com";

// 收件人电子邮箱
String to = "XXX@163.com";

// 指定发送邮件的主机为 localhost
String host = "smtp.gmail.com";

// 获取系统属性
Properties properties = System.getProperties();

// 设置邮件服务器
properties.setProperty("mail.smtp.host", "smtp.gmail.com");
properties.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
properties.setProperty("mail.smtp.socketFactory.fallback", "false");
properties.setProperty("mail.smtp.port", "465");
properties.setProperty("mail.smtp.socketFactory.port", "465");
properties.put("mail.smtp.auth", "true");
properties.put("mail.debug", "true");
properties.put("mail.store.protocol", "pop3");
properties.put("mail.transport.protocol", "smtp");

// username 还是Gmail邮箱
final String username = from;
// 应用专用密码(app password)
final String password = "YourAppPassword";

// 获取默认session对象
Session session = Session.getDefaultInstance(properties,
new Authenticator(){
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}});

try{
// 创建默认的 MimeMessage 对象
MimeMessage message = new MimeMessage(session);

// Set From: 头部头字段
message.setFrom(new InternetAddress(from));

// Set To: 头部头字段
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to,false));

// Set Subject: 头部头字段
message.setSubject("This is the Subject Line!");

// 设置消息体
message.setText("This is actual message");

// 发送消息
Transport.send(message);
System.out.println("Sent message successfully....");
}catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
Author: TheOutsider
Link: http://yoursite.com/2020/05/13/Java%E5%8F%91%E9%80%81%E9%82%AE%E4%BB%B6/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.