-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsendEmail.java
More file actions
82 lines (67 loc) · 3.16 KB
/
sendEmail.java
File metadata and controls
82 lines (67 loc) · 3.16 KB
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
package test;
import java.util.Calendar;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class sendEmail {
@SuppressWarnings("static-access")
public static void sendMessage(String smtpHost, String from,
String fromUserPassword, String to, String subject,
String messageText, String messageType) throws MessagingException {
// 第一步:配置javax.mail.Session对象
System.out.println("为" + smtpHost + "配置mail session对象");
Properties props = new Properties();
props.put("mail.smtp.host", smtpHost);
props.put("mail.smtp.starttls.enable","true");//使用 STARTTLS安全连接
//props.put("mail.smtp.port", "25"); //google使用465或587端口
props.put("mail.smtp.auth", "true"); // 使用验证
//props.put("mail.debug", "true");
Session mailSession = Session.getInstance(props,new MyAuthenticator(from,fromUserPassword));
// 第二步:编写消息
System.out.println("编写消息from——to:" + from + "——" + to);
InternetAddress fromAddress = new InternetAddress(from);
InternetAddress toAddress = new InternetAddress(to);
MimeMessage message = new MimeMessage(mailSession);
message.setFrom(fromAddress);
message.addRecipient(RecipientType.TO, toAddress);
message.setSentDate(Calendar.getInstance().getTime());
message.setSubject(subject);
message.setContent(messageText, messageType);
// 第三步:发送消息
Transport transport = mailSession.getTransport("smtp");
transport.connect(smtpHost,"17751780179@163.com","zjkdjra1750");
transport.send(message,new Address[]{new InternetAddress("851071347@qq.com")});
System.out.println("message yes");
}
public static void main(String[] args) {
try {
sendEmail.sendMessage("smtp.163.com", "17751780179@163.com",
"zjkdjra1750", "851071347@qq.com", "根据你最近关注的内容推荐给你相关竞赛",
"第二届LOL高校邀请赛<a href=\"http://www.baidu.com\">点击查看</a>",
"text/html;charset=utf-8");
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class MyAuthenticator extends Authenticator{
String userName="";
String password="";
public MyAuthenticator(){
}
public MyAuthenticator(String userName,String password){
this.userName=userName;
this.password=password;
}
protected PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication(userName, password);
}
}