qq邮箱提供smtp服务分两种,一种是企业邮箱(默认是开启的);另外一种是个人邮箱(需要自己开启,并且获得认证码)
如下代码实现,这个是默认是基于企业邮箱的实现:
package com.test;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
import java.util.Date;
import java.util.Properties;
public class TestSendMail {
public static void main(String[] args) throws Exception {
String protocol = "smtp";
String userName = "****@***.cn";//你的邮箱地址
//qq 企业邮箱的链接方式
String smtpServer ="smtp.exmail.qq.com";
String password = "*****";
//qq 个人邮箱链接方式
//String password = "*********"; qq个人邮箱需要自己开启 smtp服务,需要发短信验证,开启完成会给你一个认证码
//String smtpServer = "smtp.qq.com"; qq个人邮箱服务
String from ="******@*****.cn";
String to = "*******@***.com";
Properties props = new Properties();
props.setProperty("mail.transport.protocol", protocol);
props.setProperty("mail.host", smtpServer);
props.setProperty("mail.smtp.auth", "true");
props.put("mail.user", userName);
props.put("mail.password", password);
// 构建授权信息,用于进行SMTP进行身份验证
Authenticator authenticator = new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
String userName = props.getProperty("mail.user");
String password = props.getProperty("mail.password");
return new PasswordAuthentication(userName, password);
}
};
Session session = Session.getInstance(props, authenticator);
session.setDebug(true);//可以看调适信息
//创建代表邮件的MimeMessage对象
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
message.setSentDate(new Date());
String subject = "测试邮件";
String body = "authenticator 测试";
// 使用指定的base64方式编码,并指定编码内容的字符集是gb2312
message.setSubject(MimeUtility.encodeText(subject)); //B为base64方式
message.setText(body); //B为base64方式
//保存并且生成邮件对象
message.saveChanges();
//建立发送邮件的对象
Transport.send(message);
}
}