导包
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.7</version>
</dependency>
<dependency>
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
<version>1.1.1</version>
</dependency>
编写程序
package com.Google;
import com.sun.mail.util.MailSSLSocketFactory;
import javax.imageio.spi.ImageInputStreamSpi;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
public class mailTest {
public static void main(String[] args) throws Exception {
Properties prop = new Properties();
prop.setProperty("mail.host","stmp.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.ssl.socketFactory",sf);
//使用javaMail发送邮箱的五个步骤
//1,创建整个应用程序所需的环境信息的Session对象
Session session = Session.getDefaultInstance(prop, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
//发件人邮箱用户名,授权码(Authentication,验证)
return new PasswordAuthentication("2034281740@qq.com", "授权码");
}
});
session.setDebug(true);
//2,通过Session获取transport对象
Transport transport = session.getTransport();
//3,使用邮箱的用户名和授权码,连接邮箱服务器
transport.connect("smtp.qq.com","2034281740@qq.com", "授权码");
//4,编写内容
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress("2034281740@qq.com"));//设置发件人
message.setRecipient(Message.RecipientType.TO, new InternetAddress("2034281740@qq.com"));//设置收件人
message.setSubject("叫我靓仔");//设置邮件标题
message.setContent("叼毛,叼毛","text/html;charset=UTF-8");
//5,发送邮箱
transport.sendMessage(message, message.getAllRecipients());
}
}