java 发送email

来源:互联网 发布:数据库管理系统的是 编辑:程序博客网 时间:2024/06/05 16:31

/**
  * 发送邮件
  * @param smtp 邮件服务器
  * @param sername 用户名
  * @param serpwsd 密码
  * @param subject 主题
  * @param from 发件人
  * @param to 收件人
  * @param text 邮件的MimeBodyPart
  * @param pdfPath pdf文件路径
  * @param mimeType 邮件的mime类型
  * @return
  * @throws Exception
  */
 public boolean sendMail(String text, String to, String subject) throws Exception {

  javax.mail.Session mailSession;
  javax.mail.internet.MimeMessage mimeMsg;

  Properties props = java.lang.System.getProperties();
  props.load(EmailAgent.class.getResourceAsStream("/epolicyconfig.properties"));
  javax.mail.Authenticator auth = new CusAuthenticator(props.getProperty("username"), props.getProperty("password"));

  mailSession = javax.mail.Session.getInstance(props, auth);

  javax.mail.Transport transport = mailSession.getTransport("smtp");
  mimeMsg = new javax.mail.internet.MimeMessage(mailSession);
  InternetAddress sentFrom = new InternetAddress(props.getProperty("from"));
  mimeMsg.setFrom(sentFrom);
  mimeMsg.setRecipients(javax.mail.internet.MimeMessage.RecipientType.TO,
    InternetAddress.parse(to, false));
  mimeMsg.setSubject(subject, "gb2312");
  MimeBodyPart messageBodyPart1 = new MimeBodyPart();

  messageBodyPart1.setContent(text, "text/html;charset=gb2312");
  Multipart multipart = new MimeMultipart();
  multipart.addBodyPart(messageBodyPart1);
 
  mimeMsg.setContent(multipart);

  mimeMsg.setSentDate(new Date());
  mimeMsg.saveChanges();

  javax.mail.Transport.send(mimeMsg);
  transport.close();

  return true;
 }
 public static String getEmailContent(String emailpath) throws Exception{
  FileInputStream fis=null;
  InputStreamReader isr=null;
  BufferedReader br = null;
  StringBuffer sb=new StringBuffer();
  try{
   fis=new FileInputStream(emailpath);
   isr=new InputStreamReader(fis, "GB2312");
   br = new BufferedReader(isr);
   String value =br.readLine();
   
   while(value!=null&&value.trim().length()>1){
    sb.append(value);
    value=br.readLine();
   }
   return sb.toString();
  }catch(Exception e){
   throw new Exception(e.getMessage());
  }finally{
   if(fis!=null){
    fis.close();
   }
   if(isr!=null){
    isr.close();
   }
   if(br!=null){
    br.close();
    }
   }
  }
 

原创粉丝点击