发送简单文本邮件
发送邮件需要导入两个jar包,activation.jar 还有mail.jar
<!-- https://mvnrepository.com/artifact/javax.activation/activation -->
<dependency>
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
<version>1.1.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.mail/mail -->
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.7</version>
</dependency>
使用qq邮箱发送,需要配置一些参数
这里我是用配置文件来存储,创建了一个mail.properties文件
mail.host=smtp.qq.com
mail.transport.protocol=smtp
mail.smtp.auth=true
mail=245364863@qq.com
auth=mxtpuetxmvhnbhcx
send.mail=1764046286@qq.com
使用邮箱最主要的三个类,Session、Message、transport
@Test
public void sendMail() throws Exception {
//通过类加载器加载
InputStream is = Mail01.class.getClassLoader().getResourceAsStream("mail.properties");
//通过绝对路径
//FileInputStream is = new FileInputStream("E:\\ideaWorkSpaces\\servlet\\src\\main\\resources\\mail.properties");
Properties properties = new Properties();
properties.load(is);
//关于qq邮箱,还要设置ssl加密
MailSSLSocketFactory mailSSLSocketFactory = new MailSSLSocketFactory();
mailSSLSocketFactory.setTrustAllHosts(true);
properties.put("mail.smtp.ssl.enable","true");
properties.put("mail.smtp.ssl.socketFactory",mailSSLSocketFactory);
//创建session对象
//qq才有,其他不用
Session session = Session.getDefaultInstance(properties, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
//发件人邮件用户密码、授权码
return new PasswordAuthentication((String) properties.get("mail"), (String) properties.get("auth"));
}
});
session.setDebug(true);
//通过session获得transport对象
Transport transport = session.getTransport();
//连接服务器
transport.connect((String) properties.get("mail.host"),(String) properties.get("mail"),(String) properties.get("auth"));
//创建邮件 传递session
Message message = new MimeMessage(session);
//指明发送邮件的人
message.setFrom(new InternetAddress((String) properties.get("mail")));
//指明收件人
message.setRecipient(Message.RecipientType.TO,new InternetAddress((String) properties.get("send.mail")));
//邮件的标题
message.setSubject("hello bill");
//设置文件的内容
message.setContent("<h1 style='color:red'>小玲你钱被偷了!bill</h1>","text/html;charset=UTF-8");
//发送邮件
transport.sendMessage(message,message.getAllRecipients());
//关闭连接
transport.close();
}