0%

java发送邮件

简介

采用SMTP规则

代码

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
package ruozedata.homework.March18.join;

import com.sun.mail.util.MailSSLSocketFactory;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

public class MsgUtils {

public static void send(String recivers, String title, String content) throws Exception {

Properties properties = new Properties();
properties.setProperty("mail.host","smtp.qq.com");
properties.setProperty("mail.transport.protocol","smtp");
properties.setProperty("mail.smtp.auth", "true");
properties.setProperty("mail.smtp.ssl.enable","true");

MailSSLSocketFactory factory = new MailSSLSocketFactory();
factory.setTrustAllHosts(true);
properties.put("mail.smtp.ssl.socketFactory", factory);

Authenticator authenticator = new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
String username = "xx@qq.com";
String password = "";
return new PasswordAuthentication(username, password);
}
};
Session session = Session.getInstance(properties, authenticator);

MimeMessage message = new MimeMessage(session);
InternetAddress from = new InternetAddress("xx@qq.com");
message.setFrom(from);
InternetAddress[] tos = InternetAddress.parse(recivers);
message.setRecipients(Message.RecipientType.TO, tos);
message.setSubject(title);
message.setContent(content, "text/html;charset=UTF-8");

Transport.send(message);
}

public static void main(String[] args) throws Exception{
send("xxx", "测试", "测试内容");
}
}