1.打开jdk的conf下的security文件的.security,找到并删除,权限问题建议复制文件修改后替换
jdk.tls.disabledAlgorithms=SSLv3, TLSv1, TLSv1.1, RC4, DES, MD5withRSA, \
DH keySize < 1024, EC keySize < 224, 3DES_EDE_CBC, anon, NULL
删除后的内容
然后导入jar包:两个
授权码:邮箱-设置-账户,下滑自行获取
代码:
import com.sun.mail.util.MailSSLSocketFactory;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.security.GeneralSecurityException;
import java.util.Properties;
public class MailDemo01 {
public static void main(String[] args) throws GeneralSecurityException, MessagingException {
Properties prop=new Properties();
prop.setProperty("mail.host","smtp.qq.com");//设置qq邮件服务器
prop.setProperty("mail.transport.protocol","smtp");//邮件发送协议
prop.setProperty("mail.smtp.auth","true");//验证用户账号密码
//要设置ssl加密,固定代码,针对大厂
MailSSLSocketFactory sf=new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
prop.put("mail.smtp.ssl.enable","true");
prop.put("mail.smtp.ssl.socketFactory",sf);
//发送邮件,五个步骤
//1.创建定义整个应用程序所需的环境信息的 session 对象
//qq才有
Session session=Session.getDefaultInstance(prop, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("@qq.com","授权码");
}
});
//开启session的debug,查看邮件发送的运行状态
session.setDebug(true);
//2.通过session得到transport
Transport ts=session.getTransport();
//3.使用邮箱的用户名和授权码连接服务器 ?
ts.connect("smtp.qq.com","@qq.com","授权码");
//4.写邮件
MimeMessage message=new MimeMessage(session);
//指明发件人
message.setFrom(new InternetAddress("@qq.com"));
//收件人
message.setRecipient(Message.RecipientType.TO,new InternetAddress("@qq.com"));
//邮件标题
message.setSubject("纯文本邮件");
//邮件内容
message.setContent("<h1 style='color:red'>你好啊!<h1>","text/html;charset=UTF-8");
//5.发送邮件
ts.sendMessage(message,message.getAllRecipients());
//6.关闭连接
ts.close();
}
}