JavaMail 发送邮件例证(包括附件,及信息,及html内容的图片处理)

JavaMail 发送邮件例子(包括附件,及信息,及html内容的图片处理)

public   void   SendMessage(String   msghtm)   {  
      String   to   =   "name@21cn.com";  
      String   from   =   "name@21cn.com";  
      String   subject   =   "testhtml你好";  
      String   mailhost   =   "smtp.21cn.com";  
      String   content="<html><head>   你好   !</head><body><a   href='http://www.sina.com'>content</a><br>contentcontentcontentcontent</body></html>";  
      MimeMessage   mimeMsg   =   null;  
      Session   session   =   null;  
      String   fileAttachment   =   "C:\\mm.jpg";  
      try   {  
          Properties   props   =   System.getProperties();     //获得系统属性  
          props.put("mail.smtp.host",   mailhost);             //设置SMTP主机  
          props.put("mail.transpont.protocol","smtp");  
          props.put("mail.smtp.auth","true");  
          session   =   Session.getInstance(props,new   PassAuth("name","pass"));  
          mimeMsg   =   new   MimeMessage(   session   );  
          mimeMsg.setFrom(new   InternetAddress(   from   )   );  
          if(to!=null){  
                mimeMsg.setRecipients(   Message.RecipientType.TO,   InternetAddress.parse(   to   )   );  
          }  
          mimeMsg.setSubject(subject,"GB2312");  
          //   第一部分信息  
          MimeBodyPart   mbp1   =   new   MimeBodyPart();  
          mbp1.setText(   content,   "GB2312");  
          //   第二部分信息  
          MimeBodyPart   mbp2   =   new   MimeBodyPart();  
          FileDataSource   fds   =   new   FileDataSource(   fileAttachment   );  
          mbp2.setDataHandler(new   DataHandler(fds));  
          mbp2.setFileName(fds.getName());  
          mbp2.setHeader("Content-ID","image1");  
          //   在第三部分信息中附加一个文件  
          StringBuffer   msg=new   StringBuffer();  
          String   line="";  
          FileReader   fr=new   FileReader("c:\\test.htm");  
          BufferedReader   br=new   BufferedReader(fr);  
          while((line=br.readLine())!=null){  
              msg.append(line);  
          }  
          BodyPart   mbp3=new   MimeBodyPart();  
          mbp3.setContent(msg.toString(),"text/html;charset=gb2312");  
   
          //   创建   Multipart   并放入每个   MimeBodyPart  
          Multipart   mp   =   new   MimeMultipart("related");  
          mp.addBodyPart(   mbp1   );  
          mp.addBodyPart(   mbp2   );  
          mp.addBodyPart(   mbp3);  
         
     
   
          mimeMsg.setContent(mp);  
          //mimeMsg.setContent(msghtm,"text/html;charset=gb2312");  
          mimeMsg.setDisposition("Inline");  
          mimeMsg.setSentDate(new   Date());  
          Transport.send(   mimeMsg   );  
          System.out.println("email   send!");  
      }   catch   (MessagingException   e)   {  
          e.printStackTrace();  
      }   catch   (Exception   e)   {  
          e.printStackTrace();  
      }  
  }