需要导入的jar包:mail.jar和activation.jar
package mail; import java.util.Properties; import javax.mail.*; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; public class MailUtilsQQ587 { // 收件人,邮件主题及邮件内容通过参数形式传递 public static void sendMail(String emailAddr,String emailSub,String emailMsg) throws MessagingException { // 创建Properties 类用于记录邮箱的一些属性 Properties props = new Properties(); // SMTP发送邮件,必须进行身份验证 props.put("mail.smtp.auth", "true"); //SMTP服务器 props.put("mail.smtp.host", "smtp.qq.com"); //端口号,QQ邮箱给出了两个端口,587与465 props.put("mail.smtp.port", 587); //如果使用465端口,必须开启ssl协议 //props.put("mail.smtp.ssl.enable", "true"); // qq邮箱账号 props.put("mail.user", "**********@qq.com"); // 16位qq邮箱授权码 props.put("mail.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 mailSession = Session.getInstance(props, authenticator); // 邮件消息 MimeMessage message = new MimeMessage(mailSession); // 发件人邮箱 InternetAddress form = new InternetAddress(props.getProperty("mail.user")); message.setFrom(form); // 收件人邮箱 InternetAddress to = new InternetAddress(emailAddr); message.setRecipient(MimeMessage.RecipientType.TO, to); // 邮件标题 message.setSubject(emailSub); // 邮件内容体 message.setContent(emailMsg, "text/html;charset=UTF-8"); // 发送邮件 Transport.send(message); } }