import java.util.Date;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class Test {
static class MyPwd extends Authenticator{
private String name;
private String pwd;
public MyPwd(String name,String pwd){
this.name=name;
this.pwd=pwd;
}
@Override
protected PasswordAuthentication getPasswordAuthentication() {
// TODO Auto-generated method stub
return new PasswordAuthentication(name, pwd);
}
}
/**
* @param args
* @throws MessagingException
*/
public static void main(String[] args) throws MessagingException {
String from ="发家人的邮箱地址";
Properties pro=new Properties();
//设置发件人的服务器
pro.put("mail.smtp.host", "smtp.163.com");
//设置登录服务器是需要身份验证
pro.put("mail.smtp.auth", "true");
MyPwd my=new MyPwd("发件人账号@号前面部分", "//发件人密码");
//登陆服务器,创建于服务器之间的链接
Session session=Session.getDefaultInstance(pro,my);
//创建一个邮件的对象(消息)
Message message=new MimeMessage(session);
//标题
message.setSubject("我的第一个邮件");
//时间
message.setSentDate(new Date());
//正文
String msg="<a href='http://www.baidu.com'>百度</a>";
message.setContent(msg, "text/html;charset=UTF-8");
//message.setText(msg);
//发件人邮箱
Address fromAddress=new InternetAddress(from);
message.setFrom(fromAddress);
//收件人邮箱
/*Address toAddress=new InternetAddress("11111111@qq.com");
message.setRecipient(Message.RecipientType.TO, toAddress);*/
Address[] tos={
new InternetAddress(“//发送到的邮箱地址"),//可群发
};
message.setRecipients(Message.RecipientType.TO, tos);
//发送
Transport.send(message);
/*Transport trans= session.getTransport();
trans.send(message);
trans.close();*/
System.out.println("123");
}
}
功能所用包:activation.jar mail.jar