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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3177616/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 17:06:27  来源:igfitidea点击:

How to attach multiple files to an email using JavaMail?

javajavamail

提问by lakshmi

The following Java code is used to attach a file to an email. I want to send multiplefiles attachments through email. Any suggestions would be appreciated.

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

public class SendMail {

    public SendMail() throws MessagingException {
        String host = "smtp.gmail.com";
        String Password = "mnmnn";
        String from = "[email protected]";
        String toAddress = "[email protected]";
        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);
        }
    }
}` 

采纳答案by Jon Skeet

Well, it's been a while since I've done JavaMail work, but it looks like you could just repeat this code multiple times:

好吧,我已经有一段时间没有完成 JavaMail 工作了,但看起来您可以多次重复此代码:

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

For example, you could write a method to do it:

例如,您可以编写一个方法来执行此操作:

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);
}

Then from your main code, just call:

然后从您的主代码中,只需调用:

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

etc

等等

回答by Nikolaus Gradwohl

just add another block with using the filename of the second file you want to attach and insert it before the message.setContent(multipart) command

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

    messageBodyPart = new MimeBodyPart();

    DataSource source = new FileDataSource(filename);

    messageBodyPart.setDataHandler(new DataHandler(source));

    messageBodyPart.setFileName(filename);

    multipart.addBodyPart(messageBodyPart);

回答by Aaron Digulla

Just add more files to the multipart.

只需将更多文件添加到multipart.

回答by Omkar

    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);

回答by KRISHNA JAYANTH

Have Array list al which has the list of attachments you need to mail and use the below given code

拥有 Array list al,其中包含您需要邮寄的附件列表,并使用下面给出的代码

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);
            }

回答by Nam

UPDATE (March 2020)

更新(2020 年 3 月)

With the latest JavaMail? API(version 1.6at the moment, JSR 919), things are much simpler:

用最新的JavaMail?API(目前版本 1.6JSR 919),事情要简单得多:



Useful reading

有用的阅读

Here is a nice and to the point tutorial with the complete example:

这是一个带有完整示例的不错且中肯的教程:

回答by vikasramireddy

 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);

        }

回答by satish

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);
    }
}

回答by Zigri2612

After Java Mail 1.3 attaching file more simpler,

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

  • Just use MimeBodyPart methods to attach file directly or from a filepath.

    MimeBodyPart messageBodyPart = new MimeBodyPart();
    
    //messageBodyPart.attachFile(String filePath);
    messageBodyPart.attachFile(File file);
    
    multipart.addBodyPart(messageBodyPart);
    
  • 只需使用 MimeBodyPart 方法直接或从文件路径附加文件。

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

回答by Sam

This is woking 100% with Spring 4+. You will have to enable less secure option on your gmail account. Also you will need the apache commons package:

这在 Spring 4+ 中 100% 有效。您必须在您的 Gmail 帐户上启用安全性较低的选项。您还需要 apache commons 包:

<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.4</version>
</dependency>
@GetMapping("/some-mapping")
public void mailMethod(@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);
            }
        }
    });
}