导入mail.jar
使用mailUtils
public class MailUtils {
//email:邮件发给谁 subject:主题 emailMsg:邮件的内容
public static void sendMail(String reseiveEmail, String subject, String emailMsg)
throws AddressException, MessagingException {
//你的QQ邮箱
String sendEmail = "2281795274@qq.com";
//发送邮件的服务器地址
String emailHost = "smtp.qq.com";
//QQ邮箱授权码 开通POP3/SMTP服务 的授权码
String eMailAuthPassword = "igclafujzeuuecbh";
// 1.创建一个程序与邮件服务器会话对象 Session
Properties props = new Properties();
props.setProperty("mail.transport.protocol", "SMTP");//发邮件的协议
props.setProperty("mail.host", emailHost);//发送邮件的服务器地址
props.setProperty("mail.smtp.auth", "true");// 指定验证为true
props.setProperty("mail.password",eMailAuthPassword); //QQ邮箱授权码
//下面这三句很重要,如果没有加入进去,qq邮箱会验证不成功,一直报503错误
props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.setProperty("mail.smtp.port", "465");
props.setProperty("mail.smtp.socketFactory.port", "465");
//创建session
Session session = Session.getInstance(props);
// 2.创建一个Message,它相当于是邮件内容
Message message = new MimeMessage(session);
// 设置发送者
message.setFrom(new InternetAddress(sendEmail));
// 设置发送方式与接收者
message.setRecipient(RecipientType.TO, new InternetAddress(reseiveEmail));
//邮件的主题
message.setSubject(subject);
//邮件的内容与设置编码格式
message.setContent(emailMsg, "text/html;charset=utf-8");
//3.发送消息
Transport transport=session.getTransport("SMTP");
transport.connect(emailHost,sendEmail,eMailAuthPassword);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
}
}
获取授权码的方法
QQ邮箱—>设置—>账户—>
测试发送邮件
public class SendMailTest {
public static void main(String[] args) throws AddressException, MessagingException {
MailUtils.sendMail("2208381887@qq.com", "测试邮件","这是一封测试邮件");
}
}