这个邮箱发送需要mail-1.4.7.jar的包
以下是代码,有点粗糙
public class EmailUtil {
// 邮件主题
static String title = "";
// 被发送的的用户邮箱
static String user= "";
// 内容
static String content = "";
// 验证码有效时间(秒)
static int session;
// 发件人地址
static String fromAddress;
// 发送邮件的服务器
static String host;
// 发送邮箱账户
static String userName;
// 发送邮箱密码
static String passsWord;
public static void send(String user){
if(getProperties()){
// 内容
String content = content1+verifyCode+content2;
//1、创建连接对象
Properties props = new Properties();
//1.1设置邮件发送的协议
props.put("mail.transport.protocol" , "SMTP");
//1.2设置发送邮件的服务器
try {
props.put("mail.smtp.host" , host);
//1.3需要经过授权,也就是有户名和密码的校验,这样才能通过验证(一定要有这一条)
props.put("mail.smtp.auth" , "true");
//1.5认证信息
Session session=Session.getInstance(props , new Authenticator() {
protected PasswordAuthentication
getPasswordAuthentication(){
//用户密码
return new PasswordAuthentication(userName , passsWord);
}
});
// 2、创建邮件对象
Message message = new MimeMessage( session );
//2.1设置发件人
message.setFrom( new InternetAddress(fromAddress) );
//2.2设置收件人
message.setRecipient(RecipientType.TO , new InternetAddress( user));
//2.3设置抄送者(PS:没有这一条网易会认为这是一条垃圾短信,而发不出去)
// message.setRecipient(RecipientType.CC , new InternetAddress("[email protected]"));
//2.4设置邮件的主题
message.setSubject(title);
//2.5设置邮件的内容
message.setContent(""+content+"", "text/html;charset=utf-8");
// 3、发送邮件
Transport.send(message);
} catch (AddressException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static boolean getProperties() {
String classPath = EmailUtil.class.getResource("EmailUtil.class")
.toString();
System.out.println("classPath:" + classPath);
try {
String classFilePath = classPath;
if (classFilePath.startsWith("file:/"))
classFilePath = classFilePath.substring(6);
classFilePath = classFilePath.replace("%20", " ");
int pos = classFilePath.lastIndexOf(47);
String file = classFilePath.substring(0, pos + 1);
file = file + "email.properties";
InputStream is;
is = new FileInputStream(file);
Properties p = new Properties();
p.load(is);
title = p.getProperty("title");
content = p.getProperty("content1");
fromAddress = p.getProperty("fromAddress");
host = p.getProperty("host");
userName = p.getProperty("userName");
passsWord = p.getProperty("passsWord");
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
}