- 下载mail.jar
- 打开邮箱的smtp服务(以QQ邮箱为例)
点击设置,进入账户
开启SMTP服务
记住授权码,千万别泄露
- 测试代码:
package test;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.MimeMessage;
public class Test {
static final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
public static void main(String[] args) {
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.qq.com");
props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
props.setProperty("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.port", "465");
props.setProperty("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.from", "2028953318@qq.com");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.user", "YuFeng");
props.put("mail.debug", "true");
Authenticator auth = new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("2028953318@qq.com", "*******");
}
};
Session session = Session.getInstance(props, auth);
try {
MimeMessage msg = new MimeMessage(session);
msg.setFrom();
msg.setRecipients(Message.RecipientType.TO,
"*@163.com");
msg.setSubject("主题");
msg.setSentDate(new Date());
try {
msg.setText(new String("正文\n".getBytes(),"UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
Transport.send(msg);
} catch (MessagingException mex) {
System.out.println("send failed, exception: " + mex);
}
}
}