如何使用JavaMail将多个文件附加到电子邮件?

以下Java代码用于将文件附加到电子邮件。 我想通过电子邮件发送多个文件附件。 任何build议,将不胜感激。

public class SendMail { public SendMail() throws MessagingException { String host = "smtp.gmail.com"; String Password = "mnmnn"; String from = "xyz@gmail.com"; String toAddress = "abc@gmail.com"; String filename = "C:/Users/hp/Desktop/Write.txt"; // Get system properties Properties props = System.getProperties(); props.put("mail.smtp.host", host); props.put("mail.smtps.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); Session session = Session.getInstance(props, null); MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); message.setRecipients(Message.RecipientType.TO, toAddress); message.setSubject("JavaMail Attachment"); BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setText("Here's the file"); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); messageBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource(filename); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(filename); multipart.addBodyPart(messageBodyPart); message.setContent(multipart); try { Transport tr = session.getTransport("smtps"); tr.connect(host, from, Password); tr.sendMessage(message, message.getAllRecipients()); System.out.println("Mail Sent Successfully"); tr.close(); } catch (SendFailedException sfe) { System.out.println(sfe); } } }` 

那么,我已经完成了JavaMail的工作已经有一段时间了,但是看起来好像你可以多次重复这个代码:

 DataSource source = new FileDataSource(filename); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(filename); multipart.addBodyPart(messageBodyPart); 

例如,你可以写一个方法来做到这一点:

 private static void addAttachment(Multipart multipart, String filename) { DataSource source = new FileDataSource(filename); BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(filename); multipart.addBodyPart(messageBodyPart); } 

然后从你的主代码,只需打电话:

 addAttachment(multipart, "file1.txt"); addAttachment(multipart, "file2.txt"); 

等等

  Multipart mp = new MimeMultipart(); MimeBodyPart mbp1 = new MimeBodyPart(); mbp1.setContent(body,"text/html"); mp.addBodyPart(mbp1); if(filename!=null) { MimeBodyPart mbp2 = null; FileDataSource fds =null; for(int counter=0;counter<filename.length;counter++) { mbp2 = null; fds =null; mbp2=new MimeBodyPart(); fds = new FileDataSource(filename[counter]); mbp2.setDataHandler(new DataHandler(fds)); mbp2.setFileName(fds.getName()); mp.addBodyPart(mbp2); } } msg.setContent(mp); msg.setSentDate(new Date()); Transport.send(msg); 

现在(用JavaMail 1.4),事情比较简单:

 messageBodyPart.attachFile(File file) 

要么:

messageBodyPart.attachFile(String filePath)

只需使用要附加的第二个文件的文件名添加另一个块,并将其插入到message.setContent(multipart)命令之前

  messageBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource(filename); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(filename); multipart.addBodyPart(messageBodyPart); 

只需将更多文件添加到multipart

有Array列表,其中包含您需要发送的附件列表,并使用下面给出的代码

 for(int i=0;i<al.size();i++) { System.out.println(al.get(i)); messageBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource((String)al.get(i)); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName((String)al.get(i)); multipart.addBodyPart(messageBodyPart); message.setContent(multipart); } 
  Multipart multipart = new MimeMultipart("mixed"); for (int alen = 0; attlen < attachments.length; attlen++) { MimeBodyPart messageAttachment = new MimeBodyPart(); fileName = ""+ attachments[attlen]; messageAttachment.attachFile(fileName); messageAttachment.setFileName(attachment); multipart.addBodyPart(messageAttachment); } 
 File f = new File(filepath); File[] attachments = f.listFiles(); // Part two is attachment for( int i = 0; i < attachments.length; i++ ) { if (attachments[i].isFile() && attachments[i].getName().startsWith("error")) { messageBodyPart = new MimeBodyPart(); FileDataSource fileDataSource =new FileDataSource(attachments[i]); messageBodyPart.setDataHandler(new DataHandler(fileDataSource)); messageBodyPart.setFileName(attachments[i].getName()); messageBodyPart.setContentID("<ARTHOS>"); messageBodyPart.setDisposition(MimeBodyPart.INLINE); multipart.addBodyPart(messageBodyPart); } } 

Java Mail 1.3附加文件更简单后,

  • 只需使用MimeBodyPart方法直接或从文件path附加文件。

     MimeBodyPart messageBodyPart = new MimeBodyPart(); //messageBodyPart.attachFile(String filePath); messageBodyPart.attachFile(File file); multipart.addBodyPart(messageBodyPart); 

这跟Spring 4+有100%的差距

 @RequestParam CommonsMultipartFile attachFile; @RequestParam CommonsMultipartFile attachFile2; Properties mailProperties = new Properties(); mailProperties.put("mail.smtp.auth", true); mailProperties.put("mail.smtp.starttls.enable", true); mailProperties.put("mail.smtp.ssl.enable", true); mailProperties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); mailProperties.put("mail.smtp.socketFactory.fallback", false); JavaMailSenderImpl javaMailSenderImpl = new JavaMailSenderImpl(); javaMailSenderImpl.setJavaMailProperties(mailProperties); javaMailSenderImpl.setHost("smtp.gmail.com"); javaMailSenderImpl.setPort(465); javaMailSenderImpl.setProtocol("smtp"); javaMailSenderImpl.setUsername("*********@gmail.com"); javaMailSenderImpl.setPassword("*******"); javaMailSenderImpl.setDefaultEncoding("UTF-8"); List<CommonsMultipartFile> attachments = new ArrayList<>(); attachments.add(attachFile); attachments.add(attachFile2); javaMailSenderImpl.send(mimeMessage -> { MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true, "UTF-8"); messageHelper.setTo(emailTo); messageHelper.setSubject(subject); messageHelper.setText(message); if (!attachments.equals("")) { for (CommonsMultipartFile file : attachments) { messageHelper.addAttachment(file.getOriginalFilename(), file); } } });