使用之前需要先下载javamail的jar包

代码入下,持续更新中。。。

这里以搜狐邮箱为例,其他邮箱可以前往邮箱官网查看配置

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
import javax.mail.*;
import javax.mail.internet.*;
import java.util.Properties;

public class Main {
public static void sendSimpleMail() throws MessagingException {
//账号
String userName = "xxxx@sohu.com";

//密码(官网生成的校验码)
String password = "XXXXXXXXXXX";

//接收方邮箱
String to = "xxx@qq.com";

//标题
String subject = "标题";

//内容
String text = "内容";


Properties props = new Properties();
//设置服务器
props.put("mail.smtp.host", "smtp.sohu.com");
//服务器端口
props.put("mail.smtp.port", "465");

//验证


props.put("mail.smtp.auth", true);
props.put("mail.smtp.ssl.enable", "true");
props.put("mail.smtp.ssl.protocols", "TLSv1.2");


Session session = Session.getInstance(props, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, password);
}
});


Message message = new MimeMessage(session);

//邮件主题
message.setSubject(subject);
//邮件内容
message.setText(text);
//设置邮件的发送方
InternetAddress form = new InternetAddress(userName);
message.setFrom(form);

//设置邮件接收方
message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));


Transport.send(message);
System.out.println("发送成功");


}


public static void main(String[] args) throws MessagingException {
sendSimpleMail();
}
}