一、新建一个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");
MailSSLSocketFactory mailSSLSocketFactory = new MailSSLSocketFactory();
mailSSLSocketFactory.setTrustAllHosts(true);
properties.put("mail.smtp.ssl.enable","true");
properties.put("mail.smtp.ssl.socketFactory",mailSSLSocketFactory);
Session session = Session.getDefaultInstance(properties, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("11111111@qq.com", 校验码);
}
});
session.setDebug(true);
Transport transport = session.getTransport();
transport.connect("smtp.qq.com","11111111@qq.com",校验码);
MimeMessage mimeMessage = new MimeMessage(session);
mimeMessage.setFrom(new InternetAddress("11111111@qq.com"));
mimeMessage.setRecipient(Message.RecipientType.TO,new InternetAddress("22222222@qq.com"));
mimeMessage.setSubject("只包含文本的简单邮件");
mimeMessage.setContent("<h1 style=\"color:red;\">你好啊!</h1>", "text/html;charset=UTF-8");
transport.sendMessage(mimeMessage,mimeMessage.getAllRecipients());
transport.close();
}
}
|