java发送邮件

闲来无事,写个java发送邮件玩玩。核心代码如下:
private boolean mailSend (String fromMail,String toMail,String subject,String strContext){
		  try {
			  Properties props = new Properties();
			  props.put("mail.transport.protocol","smtp");
			  props.put("mail.smtp.host", smtpServer); //
			  props.put("mail.smtp.auth", "true"); //认证是否设置
			  props.put("mail.host",smtpServer);
			  //建立会话并且认证
			  Authenticator auth1 = new Authenticator() {//封装用户名 密码
				  public PasswordAuthentication getPasswordAuthentication() {
					  return new PasswordAuthentication(username,psw);
				  }
			  };
			  javax.mail.Session session =javax.mail.Session.getInstance(props,auth1);
			  Message msg = new MimeMessage(session);
			  //发送源地址
			  msg.setFrom(new InternetAddress(fromMail));
			  //发送目的地址
			  ArrayList<String> altMail = this.parseMailAddress(toMail);
			  InternetAddress[] tos = new InternetAddress[altMail.size()];
			  for(int j = 0;j<altMail.size();j++){
				  tos[j] = new InternetAddress(altMail.get(j).toString());
			  }
			  if(tos.length == 0) return false;
			  msg.setRecipients(Message.RecipientType.TO, tos);
			  //主题
			  msg.setSubject(subject);
			  //邮件体
			  Multipart mp = new MimeMultipart();
			  //邮件内容
			  //把信件内容放入mp内,和附件一样的放发,作为一个整体发送。
			  MimeBodyPart mbps = new MimeBodyPart();
			  mbps.setContent(strContext,"text/html;charset=UTF-8");//正文内容
			  //mbps.setText(strContext);//正文内容
			  mp.addBodyPart(mbps);
		
			  //Multipart加入到信件
			  msg.setContent(mp);
			  msg.saveChanges();

			  //发送
			  Transport transport = session.getTransport("smtp");
			  transport.connect(smtpServer,username,psw);
			  transport.sendMessage(msg, msg.getAllRecipients());
			  transport.close();
			  return true;
		  }catch (Exception e) {
	      e.printStackTrace();
	      return false;
	    }
	  }

所用jar包:mail-1.3.1.jar


找到一个非常详细的文档介绍:http://www.cnblogs.com/codeplus/archive/2011/10/30/2229391.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值