jar包的支持
activation-1.1.1.jar
mail-1.4.7.jar
拿到授权码
Java
package com.dyq;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 Exception {Properties prop = new Properties();prop.setProperty("mail.host", "smtp.qq.com"); //设置QQ邮件服务区prop.setProperty("mail.transport.protocol", "smtp"); //邮件发送协议prop.setProperty("mail.smtp.auth", "true"); //需要验证用户名密码//关于QQ邮箱,还要设置SSL加密,加上以下代码即可,大厂,其他邮箱不需要MailSSLSocketFactory sf = new MailSSLSocketFactory();sf.setTrustAllHosts(true);prop.put("mail.smtp.ssl.enable", "true");prop.put("mail.smtp.socketFactory", sf);//使用JavaMail发送邮箱的5个步骤//1.创建定义整个应用程序所需的环境信息的Session对象//QQ才有,其他邮箱不用Session session = Session.getInstance(prop, new Authenticator() {@Overrideprotected PasswordAuthentication getPasswordAuthentication() {return new PasswordAuthentication("504561395@qq.com", "xkmwtqwlqsbgbgfb");}});// 开启Session的debug模式:可以看到程序发送Email的运行状态session.setDebug(true);//2.通过session得到transport对象Transport ts = session.getTransport();//3.使用邮箱的用户名和授权码连上邮件服务器ts.connect("smtp.qq.com", "504561395@qq.com", "xkmwtqwlqsbgbgfb");//4.创建邮箱:写邮件//注意需要传递SessionMessage message = new MimeMessage(session);//指明邮件的发件人message.setFrom(new InternetAddress("504561395@qq.com"));//指明收件人message.setRecipient(Message.RecipientType.TO, new InternetAddress("504561395@qq.com"));//设置邮箱标题message.setSubject("秃头小分队Demo");//文本内容message.setContent("<h1 style='color:red'>你好啊!</h1>", "text/html;charset=UTF-8");//5.发送邮件ts.sendMessage(message,message.getAllRecipients());//6.关闭ts.close();}}

