Java邮件开发-----JavaMail(二)

          这篇博客主要是介绍如何实现将邮件发送给多个收件人和如何利用Authenticators对象实现用户验证。   

         在指定收件人的时候,我们可以有两种方法来指定。上篇博客是在发送邮件的时候临时指定收件人,其实还可以在Message对象中指定。

message.addRecipient(Message.RecipientType.TO,new InternetAddress(” 995812509@99.com ”));

         这个只是发送给一个收件人而言,但是有多个收件人如何处理?同样有两种方法来处理。

          1、在发送邮件时Transport的sendMessage()方法指定收件人时是使用数组来指定收件人的,这个时候我们只需要多添加收件人地址即可完成。

          2、在使用Message对象来添加收件人我们可以使用InternetAddress对象的parse(String string)方法,该方法返回的是InternetAddress数组,这样同样可以实现发送给多个收件人。

 

         我们知道在进行JavaMail开发时我们必须要进行授权校验,授权校验目的是阻止他人任意乱发邮件,减少垃圾邮件的产生。前篇博客中我是是用的Transport的connect(host,port,username,password)方法来进行校验的,其实我们还可以在获取Session对象的时候进行校验。在Session对象中有这两个方法:getDefaultInstance(prop,authenticator),getInstance(prop,authenticator),这两个方法都有一个共同的参数authenticator,该参数是一个Authenticator对象。Authenticator对象就是帮助用户进行信息验证的,完成授权校验。Authenticator对象中有getPasswordAuthentication()方法,该方法返回返回一个PasswordAuthentication对象,PasswordAuthentication对象中有两个方法:getPassword()getUserName()也就说我们将passworduserName封装在PasswordAuthentication对象,通过这两个方法就可以获取用户名和密码了。即可完成用户信息验证。

          实例如下:

public class JavaMail_02 {
	public static void main(String[] args) throws Exception {
		Properties  props = new Properties();
		props.setProperty("mail.smtp.auth", "true");
		props.setProperty("mail.transport.protocol", "smtp");
		props.setProperty("mail.host", "smtp.163.com");
		
		Session session = Session.getInstance(props,
				new Authenticator(){
					protected PasswordAuthentication getPasswordAuthentication(){
						return new PasswordAuthentication("********","*********");
					}
		});
		session.setDebug(true);
		
		Message msg = new MimeMessage(session);
		msg.setFrom(new InternetAddress("chenssy995812509@163.com"));
		
		msg.setSubject("JavaMail测试程序...");
		msg.setContent("<span style='color:red'>这是我的第二个javaMail测试程序....</span>", "text/html;charset=gbk");
		//msg.setRecipients(RecipientType.TO, new Address[]{new InternetAddress("1111@@qq.com"),new InternetAddress("2222@qq.cpm")});
		msg.setRecipients(RecipientType.TO, InternetAddress.parse("995812509@qq.com,1247723213@qq.com"));
		
		Transport.send(msg);
	}

}


 

  • 2
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大明哥_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值