2011-09-07 71 views
0

我正在开发一个项目,我需要从SFTP服务器下载2个文件,将它们压缩成一个时间戳名称并将其保存到我的本地服务器。此外,一旦文件被检索,我希望它发送一封电子邮件,要么它成功地完成了工作或失败。我使用JSch检索SFTP服务器,并可以将文件保存在本地服务器中。任何人都可以建议我应该如何编写我的代码来压缩文件并发送电子邮件。任何帮助表示赞赏,我正在与这个小型项目的Java合作。从SFTP服务器下载压缩文件

回答

1

使用ZipOutputStreamJava Mail你应该可以做你想做的。我创建了一个示例主要方法,它接受主机,从和作为命令行参数。它假定你已经知道压缩文件名并发送一封附有zip的电子邮件。我希望这有帮助!

public class ZipAndEmail { 
    public static void main(String args[]) { 
    String host = args[0]; 
    String from = args[1]; 
    String to = args[2]; 

    //Assuming you already have this list of file names 
    String[] filenames = new String[]{"filename1", "filename2"}; 

    try { 
     byte[] buf = new byte[1024]; 
     String zipFilename = "outfile.zip"; 
     ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFilename)); 

     for (int i=0; i<filenames.length; i++) { 
     FileInputStream in = new FileInputStream(filenames[i]); 
     out.putNextEntry(new ZipEntry(filenames[i])); 
     int len; 
     while ((len = in.read(buf)) > 0) { 
      out.write(buf, 0, len); 
     } 
     out.closeEntry(); 
     in.close(); 
     } 
     out.close(); 


     Properties props = System.getProperties(); 
     props.put("mail.smtp.host", host); 
     Session session = Session.getDefaultInstance(props, null); 

     // Define message 
     MimeMessage message = new MimeMessage(session); 
     message.setFrom(new InternetAddress(from)); 
     message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); 
     message.setSubject("Your Zip File is Attached"); 

     MimeBodyPart messageBodyPart = new MimeBodyPart(); 
     messageBodyPart.setText("Your zip file is attached"); 
     Multipart multipart = new MimeMultipart(); 
     multipart.addBodyPart(messageBodyPart); 

     // Part two is attachment 
     messageBodyPart = new MimeBodyPart(); 
     DataSource source = new FileDataSource(zipFilename); 
     messageBodyPart.setDataHandler(new DataHandler(source)); 
     messageBodyPart.setFileName(zipFilename); 
     multipart.addBodyPart(messageBodyPart); 

     // Put parts in message 
     message.setContent(multipart); 

     // Send the message 
     Transport.send(message); 

     // Finally delete the zip file 
     File f = new File(zipFilename); 
     f.delete(); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
    } 
}