使用sendMail发送邮件
1发送邮件必须有邮件服务器,在这里以QQ邮箱服务器为例
设置QQ邮箱支持POP,ICMP协议(百度有设置方式,在这里不再赘述)
2 下载mail.jar(注意版本,此代码示例为1.6版本)
http://download.csdn.net/download/u011238841/9926479
3 代码示例
package com.hengc;
import java.util.Properties;
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 com.fastjrun.util.impl.BaseUtil;
/**
* @ClassName: EmailUtils
* @Description: 邮件发送
* @author kekeair
* @date 2017年9月6日 上午9:32:02
*/
public class EmailUtils extends BaseUtil {
public void sendEmail() {
// 收件人电子邮箱
String to = "zhangtingke170626@credithc.com";
// 发件人电子邮箱
final String from = "578221811@qq.com";
// 设置SSL连接、邮件环境
Properties props = System.getProperties();
props.setProperty("mail.smtp.host", "smtp.qq.com");
props.setProperty("mail.smtp.port", "587");
props.setProperty("mail.smtp.auth", "true");
// 建立邮件会话
Session session = Session.getDefaultInstance(props,
new Authenticator() {
// 身份认证
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(from,
"pfgvfdrxkoxfbced");
}
});
session.setDebug(true);
try {
// 创建默认的 MimeMessage 对象
MimeMessage message = new MimeMessage(session);
// Set From: 头部头字段
InternetAddress from_address = new InternetAddress(from);
from_address.setPersonal(MimeUtility.encodeText("kevin"));
message.setFrom(from_address);
// Set To: 头部头字段
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(to));
// Set Subject: 头部头字段
message.setSubject("This is the Subject Line!");
// 设置消息体
message.setText("http://www.baidu.com");
// 发送消息
Transport.send(message);
} catch (Exception mex) {
mex.printStackTrace();
}
}
}
注意QQ邮箱服务器,和端口号设置也就是:
props.setProperty(“mail.smtp.host”, “smtp.qq.com”);
props.setProperty(“mail.smtp.port”, “587”);