一、新建一个Maven空项目,并导包
共需要两个jar包
<dependency>
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.7</version>
</dependency>
二、去QQ邮箱取得校验码

验证之后方可获取校验码,并牢记
3、创建类
从11111111@qq.com邮箱,向22222222@qq.com发送邮件
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 Main {
public static void main(String[] args) throws Exception {
String 校验码="你的校验码";//将你的校验码放进去
Properties properties = new Properties();
properties.setProperty("mail.host","smtp.qq.com");
properties.setProperty("mail.transport.protocol","smtp");
properties.setProperty("mail.smtp.auth","true");
//关于QQ邮箱,还需要设置SSL加密
MailSSLSocketFactory mailSSLSocketFactory = new MailSSLSocketFactory();
mailSSLSocketFactory.setTrustAllHosts(true);
properties.put("mail.smtp.ssl.enable","true");
properties.put("mail.smtp.ssl.socketFactory",mailSSLSocketFactory);
//使用Java发送邮件的5步骤
// 1、定义整个应用程序所需的环境信息的Session对象
Session session = Session.getDefaultInstance(properties, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("11111111@qq.com", 校验码);
}
});
// 开启Session的deBug模式,查看运行状态
session.setDebug(true);
// 2、通过Session得到transport对象
Transport transport = session.getTransport();
// 3、使用邮箱的用户名和授权码连接服务器
transport.connect("smtp.qq.com","11111111@qq.com",校验码);
// 4、创建邮件
MimeMessage mimeMessage = new MimeMessage(session);
// 发件人
mimeMessage.setFrom(new InternetAddress("11111111@qq.com"));
// 收件人
mimeMessage.setRecipient(Message.RecipientType.TO,new InternetAddress("22222222@qq.com"));
// 邮件的标题
mimeMessage.setSubject("只包含文本的简单邮件");
// 文本内容,实际上是Html文件
mimeMessage.setContent("<h1 style=\"color:red;\">你好啊!</h1>", "text/html;charset=UTF-8");
// 5、发送邮件
transport.sendMessage(mimeMessage,mimeMessage.getAllRecipients());
// 6、关闭
transport.close();
}
}
本文介绍了如何使用Java的Maven项目通过javax.mail库实现从QQ邮箱向指定邮箱发送带有HTML内容的邮件,涉及依赖导入、配置SMTP和SSL,以及获取并使用校验码进行身份验证。
1255

被折叠的 条评论
为什么被折叠?



