java发送邮件

来源:互联网 发布:天津金蝶软件 编辑:程序博客网 时间:2024/04/30 01:53
闲来无事,写个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
原创粉丝点击