JAVA实现发送邮件
做项目时用到的小工具 做个备份(
tips:
需要导入javax.mail 我使用了maven导入X
`
<!-- JavaMail相关依赖 --><dependency><groupId>javax.mail</groupId><artifactId>javax.mail-api</artifactId><version>1.4.7</version></dependency><dependency><groupId>javax.activation</groupId><artifactId>activation</artifactId><version>1.1.1</version></dependency>
`
开启服务
总之全都开了不会错X
开启通过验证后得到授权码
package Util;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 emailutil implements Runnable {private String email;// 收件人邮箱private String code;public emailutil(String email,String code) {this.email = email;this.code = code;}@Overridepublic void run() {// 1.创建连接对象javax.mail.Session// 2.创建邮件对象 javax.mail.Message// 3.发送一封激活邮件String from = "XXXXXXX@";// 发件人电子邮箱String host = ""; // 指定发送邮件的主机(QQ)|(网易)Properties properties = System.getProperties();// 获取系统属性properties.setProperty("mail.smtp.host", host);// 设置邮件服务器properties.setProperty("mail.smtp.auth", "true");// 打开认证try {//QQ邮箱需要下面这段代码,163邮箱不需要MailSSLSocketFactory sf = new MailSSLSocketFactory();sf.setTrustAllHosts(true);properties.put("mail.smtp.ssl.enable", "true");properties.put("mail.smtp.ssl.socketFactory", sf);// 1.获取默认session对象Session session = Session.getDefaultInstance(properties, new Authenticator() {public javax.mail.PasswordAuthentication getPasswordAuthentication() {return new PasswordAuthentication("XXXXX@", "kXXXXX"); // 发件人邮箱账号、授权码}});// 2.创建邮件对象Message message = new MimeMessage(session);// 2.1设置发件人message.setFrom(new InternetAddress(from));// 2.2设置接收人message.addRecipient(Message.RecipientType.TO, new InternetAddress(email));// 2.3设置邮件主题message.setSubject("账号激活");// 2.4设置邮件内容String content = "<html><head></head><body>【内容】</body></html>";message.setContent(content, "text/html;charset=UTF-8");// 3.发送邮件Transport.send(message);System.out.println("邮件成功发送!");} catch (Exception e) {e.printStackTrace();}}}
遇到最严重最难处理的问题
邮件无法成功发送,报错:
.ssl.SSLHandshakeException: No appropriate protocol (protocol is disabled or cipher suites
将723-725注释
ate protocol (protocol is disabled or cipher suites
修改在java安装目录的java.security文件 可能要用管理员身份打开才能修改
邮件美美自动发送了