Jak dołączyć wiele plików do wiadomości e-mail za pomocą JavaMail?

Poniższy kod Java jest używany do załączania pliku do wiadomości e-mail. Chcę wysłać Wiele plików za pośrednictwem poczty elektronicznej. Wszelkie sugestie będą mile widziane.

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);
        }
    }
}` 
Author: vektor, 2010-07-05

10 answers

Cóż, minęło trochę czasu odkąd wykonałem pracę w JavaMail, ale wygląda na to, że można po prostu powtórzyć ten kod wiele razy:

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

Na przykład, możesz napisać metodę, aby to zrobić:

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

Następnie z głównego kodu, po prostu zadzwoń:

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

Etc

 46
Author: Jon Skeet,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-07-24 08:33:09
    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);
 6
Author: Omkar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-06-20 07:43:07

Teraz (z JavaMail 1.4), rzecz jest prostsza:

messageBodyPart.attachFile(File file)

Lub:

MessageBodyPart.attachFile (String filePath)

 5
Author: Nam,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-11-18 11:59:18

Wystarczy dodać kolejny blok używając nazwy pliku drugiego pliku, który chcesz załączyć i wstawić go przed wiadomością.polecenie setContent (multipart)

    messageBodyPart = new MimeBodyPart();

    DataSource source = new FileDataSource(filename);

    messageBodyPart.setDataHandler(new DataHandler(source));

    messageBodyPart.setFileName(filename);

    multipart.addBodyPart(messageBodyPart);
 2
Author: Nikolaus Gradwohl,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-07-05 06:59:40

Wystarczy dodać więcej plików do multipart.

 1
Author: Aaron Digulla,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-07-05 07:05:19

Miej listę tablic al, która zawiera listę załączników, które musisz przesłać i użyć poniższego kodu

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);
            }
 1
Author: KRISHNA JAYANTH,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-07-05 13:01:10
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);
    }
}
 1
Author: satish,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-08-05 06:42:59
 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);

        }
 0
Author: vikasramireddy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-01-09 16:03:28

Po Java Mail 1.3 dołączanie pliku jest prostsze,

  • Wystarczy użyć metod MimeBodyPart, aby załączyć plik bezpośrednio lub z ścieżki pliku.

    MimeBodyPart messageBodyPart = new MimeBodyPart();
    
    //messageBodyPart.attachFile(String filePath);
    messageBodyPart.attachFile(File file);
    
    multipart.addBodyPart(messageBodyPart);
    
 0
Author: Zigri2612,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-04-24 10:29:16

To jest woking 100% z Wiosna 4 +

@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);
        }
    }
});
 0
Author: SAM,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-11-05 21:40:29