java Mail
1.相关依赖
<dependency >
<groupId >com.sun.mail </groupId >
<artifactId >javax.mail </artifactId >
<version >1.5.4 </version >
</dependency >
2.代码
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
/**
* Created by admin on 2018/6/24.
*/
public class SendMail {
public static void main(String[] args) {
//做链接前的准备工作 也就是参数初始化
Properties properties = new Properties();
properties.setProperty("mail.smtp.host","smtp.qq.com");//发送邮箱服务器
properties.setProperty("mail.smtp.port","465");//发送端口
properties.setProperty("mail.smtp.auth","true");//是否开启权限控制
properties.setProperty("mail.debug","true");//true 打印信息到控制台
properties.setProperty("mail.transport","smtp");//发送的协议是简单的邮件传输协议
properties.setProperty("mail.smtp.ssl.enable","true");
//建立两点之间的链接
System.out.println("执行了2");
Session session = Session.getInstance(properties, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("xxx@qq.com","zraquwqtxvvhfgda");
}
});
System.out.println("执行了3");
//创建邮件对象
Message message = new MimeMessage(session);
//设置发件人
try {
message.setFrom(new InternetAddress("xxx@qq.com"));
//设置收件人
message.setRecipient(Message.RecipientType.TO,new InternetAddress("xxx@qq.com"));//收件人
//设置主题
message.setSubject("骚白给你发来一封邮件!");
//设置邮件正文 第二个参数是邮件发送的类型
message.setContent("发送的内容","text/html;charset=UTF-8");
//发送一封邮件
Transport transport = session.getTransport();
transport.connect("xxx@qq.com","zraquwqtxvvhfgda");
Transport.send(message);
System.out.println("执行了");
} catch (MessagingException e) {
e.printStackTrace();
}finally {
}
}
}
注意:
必须去qq邮箱中,账户下面开启smtp协议
开启PSP3/SMTP服务即可