[英]Zipping files downloaded from SFTP server
我正在一个项目中,我需要从SFTP服务器下载2个文件,并用时间戳名称压缩它们,然后将其保存到我的本地服务器中。 另外,一旦检索到文件,我希望它发送一封电子邮件,说明它成功完成了工作或失败了。 我正在使用JSch检索SFTP服务器,并且可以将文件保存在本地服务器中。 谁能建议我应该如何编写代码来压缩文件并发送电子邮件。 任何帮助表示赞赏,我正在为这个小项目使用Java。
使用ZipOutputStream
和Java 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();
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.