Struts+邮件发送系统(添加附件)

2011/01/04

实现邮件发送功能:

1.Struts配置以及jar包导入

2.mail.jar,activation.jar导入(邮寄发送需要这两个jar)

3.创建EMAIL.properties文件存放参数文件

serverSend=smtp.126.com
serverReceive=smtp.qq.com

4.读取配置文件,实现发送邮件,代码:

 

  public static void sendEmail(EmailBean eb){
     try {
      //String pash = System.getProperty("user.dir");
      Properties p=new Properties();
      FileInputStream  in = new  FileInputStream("D:/workspaces/Email/src/com/email/EMAIL.properties");
      p.load(in);
      serverSend = p.getProperty("serverSend");
      serverReceive = p.getProperty("serverReceive");
      userName = p.getProperty("userName");
      userPass = p.getProperty("userPass");
      sendEmail = p.getProperty("sendEmail");
      String title = eb.getTitle();
      String content = eb.getContent();
      String filef = eb.getFilef();
      String filenames[] = filef.split("\\\\");
      String filename = filenames[filenames.length-1];
      title = new String(title.getBytes("GBK"));
      content = new String(content.getBytes("GBK"));
      filename = new String(filename.getBytes("GBK"),"ISO-8859-1");
      Properties props = new Properties();
      props.put("mail.smtp.host",serverSend);//指定SMTP服务器  
      props.put("mail.smtp.auth","true");//指定是否需要SMTP验证
      Session mailSession = Session.getDefaultInstance(props);
      mailSession.setDebug(true);//是否在控制台显示debug信息    
      Message message=new MimeMessage(mailSession);  
      message.setFrom(new InternetAddress(sendEmail));//发件人  
      message.addRecipient(Message.RecipientType.TO,new InternetAddress(eb.getEmail()));//收件人     
      message.setSubject(title);//邮件主题  
      //message.setText(content);//邮件内容  
            
       MimeBodyPart messageBodyPart = new MimeBodyPart();
       messageBodyPart.setText(content);  //发送普通内容邮件

       messageBodyPart.setDataHandler(new DataHandler("<hr><hr><table><tr><td>测试</td><td>111</td></tr></table>","text/html;charset=GBK"));   //发送HTML格式邮件            
       Multipart multipart = new MimeMultipart();
       multipart.addBodyPart(messageBodyPart);

       messageBodyPart = new MimeBodyPart();
       DataSource source =  new FileDataSource(filef);//附件地址
       messageBodyPart.setDataHandler(new DataHandler(source));
       messageBodyPart.setFileName(filename);//显示附件时显示的名字
       multipart.addBodyPart(messageBodyPart);
            
       message.setContent(multipart);
       message.setSentDate(new Date());
       message.saveChanges();  
         
       Transport   transport =   mailSession.getTransport("smtp");  
       transport.connect(serverSend,userName,userPass);    
       transport.sendMessage(message,message.getAllRecipients());  
       transport.close(); 
     } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  
 }

 

EmailBean主要存放发送邮件地址,主题,内容,添加附件……

注意:附件名称显示中文乱码显示问题,要用new String(filename.getBytes("GBK"),"ISO-8859-1")进行转码……

发送HTML邮件和发送普通文本邮件不能共存……

你可能感兴趣的:(html,struts,qq)