javamail简单使用

1、导入javaMail.jar包

生成邮件内部调用了其它的API,所以要用JAF,javaBeans激活框架,是一个专用 的数据处理框架,它用于封装数据,并为应用程序提供访问和操作的数据接口。javaMailAPI可以利用JAF从某种数据源中读取数据和数据的MIME类型,并用这些数据生成MIME消息体和消息类型
2、导入JAF.jar包,JDK6不用
3、写如下代码(一种方法)


public class demo {
public static void main(String[] args)throws Exception {
Properties props = new Properties();
//两个属性必须配置
props.setProperty("mail.transport.protocol", "smtp");
//设置需要验证(给提供用户名、密码)
props.setProperty("mail.smtp.auth", "true");

//该方法每次都返回一个新的session.getDefaultInstance()方法可能返回的是之前创建的
Session session = Session.getInstance(props);
//打印与服务器交互的信息
session.setDebug(true);

Message msg = new MimeMessage(session);
msg.setText("你好!");
msg.setSubject("This is 主题");

//发件人 (可以不是真实的)
msg.setFrom(new InternetAddress("111@126.com"));

Transport transport = session.getTransport();

//设置 连接服务器、 端口、 用户名、 密码
transport.connect("smtp.126.com",25,"111@126.com","1111");

//静态的send方法 ,直接就能用(发一封邮件可以用它 要不然每发一封就要连一次服务器 效率低) (内部做了链接、发、关链接) 自己连了就不用静态方法了
//Transport.send(msg,new Address[]{new InternetAddress("532356902@qq.com")});

//非静态send方法(发多封邮件时用 只连一次服务器) 包含收件人(也可以在message里面设置 但是群发的时候 就觉得不好)
transport.sendMessage(msg, new Address[]{new InternetAddress("2222@qq.com")});

transport.close();

}

}


(二种方法)


public class demo2 {

public static void main(String[] args)throws Exception {
Properties props = new Properties();
props.setProperty("mail.transport.protocol", "smtp");
//设置需要验证(给提供用户名、密码)
props.setProperty("mail.smtp.auth", "true");
props.setProperty("mail.host", "smtp.126.com");

Session session = Session.getInstance(props,
new Authenticator(){//传递Authenticator对象,覆盖以下方法
protected PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication("111@126.com","1111");
}
}
);//产生不同的session

session.setDebug(true);
Message msg = new MimeMessage(session);//第一种产生message方式
msg.setFrom(new InternetAddress("111@126.com"));
msg.setSubject("中文主题");
msg.setContent("<span style='color:red'>呵呵</span>", "text/html;charset=gbk");
msg.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("222@qq.com,111@126.com") );

Transport.send(msg);


//第二种产生message方式
//Message msg = new MimeMessage(session,new FileInputStream("D://java.eml"));
Transport.send(msg,InternetAddress.parse("222@qq.com"));
}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值