3

I have a list of files that are created on application launch, and I want those files to be sent via email. The emails do send, but they don't have any attachments.

Here's the code:

private Multipart getAttachments() throws FileNotFoundException, MessagingException
{
   File folder = new File(System.getProperty("user.dir"));
   File[] fileList = folder.listFiles();

   Multipart mp = new MimeMultipart("mixed");

   for (File file : fileList)
   {
       // ext is valid, and correctly detects these files.
       if (file.isFile() && StringFormatter.getFileExtension(file.getName()).equals("xls")) 
       {
           MimeBodyPart messageBodyPart = new MimeBodyPart();
           messageBodyPart.setDataHandler(new DataHandler(file, file.getName()));
           messageBodyPart.setFileName(file.getName());
           mp.addBodyPart(messageBodyPart);
       }
   }
   return mp;
}

There's no error, warning, or anything else. I even tried creating a Multipart named childPart and assigning it to mp through .setParent(), and that did not work either.

I am assigning the attachments this way:

Message msg = new MimeMessage(session);
Multipart mp = getAttachments();
msg.setContent(mp); // Whether I set it here, or next-to-last, it never works.
msg.setSentDate(new Date());
msg.setFrom(new InternetAddress("addressFrom"));
msg.setRecipient(Message.RecipientType.TO, new InternetAddress("addressTo"));
msg.setSubject("Subject name");
msg.setText("Message here.");
Transport.send(msg);

How do I correctly send multiple attachments via Java?

Mark Buffalo
  • 766
  • 1
  • 10
  • 25

2 Answers2

4

This is my own email utility class, check if that the sendEmail method works for you

import java.io.File;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
public class EMail {
    
    public enum SendMethod{
        HTTP, TLS, SSL
    }

    private static final String EMAIL_PATTERN = 
            "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
            + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
    
    public static boolean isValidEmail(String address){
        return (address!=null && address.matches(EMAIL_PATTERN));
    }

    public static String getLocalHostName() {
        try {
            return InetAddress.getLocalHost().getHostName();
        } catch (UnknownHostException e) {
            return "localhost";
        }
    }

    public static boolean sendEmail(final String recipients, final String from,
            final String subject, final String contents,final String[] attachments,
            final String smtpserver, final String username, final String password, final SendMethod method) {
        
        Properties props = System.getProperties();
        props.setProperty("mail.smtp.host", smtpserver);
        
        Session session = null;
        
        switch (method){
        case HTTP:
            if (username!=null) props.setProperty("mail.user", username);
            if (password!=null) props.setProperty("mail.password", password);
            session = Session.getDefaultInstance(props);
            break;
        case TLS:
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.starttls.enable", "true");
            props.put("mail.smtp.port", "587");
            session = Session.getInstance(props, new Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication(){
                    return new PasswordAuthentication(username, password);
                }
            });
            break;
        case SSL:
            props.put("mail.smtp.socketFactory.port", "465");
            props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.port", "465");
            session = Session.getDefaultInstance(props, new Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication(){
                    return new PasswordAuthentication(username, password);
                }
            });
            break;
        }
        
        try {
            MimeMessage message = new MimeMessage(session);
            
            message.setFrom(from);
            message.addRecipients(Message.RecipientType.TO, recipients);
            message.setSubject(subject);
            
            Multipart multipart = new MimeMultipart();
            
            BodyPart bodypart = new MimeBodyPart();
            bodypart.setContent(contents, "text/html");
            
            multipart.addBodyPart(bodypart);
            
            if (attachments!=null){
                for (int co=0; co<attachments.length; co++){
                    bodypart = new MimeBodyPart();
                    File file = new File(attachments[co]);
                    DataSource datasource = new FileDataSource(file);
                    bodypart.setDataHandler(new DataHandler(datasource));
                    bodypart.setFileName(file.getName());
                    multipart.addBodyPart(bodypart);
                }
            }
            
            message.setContent(multipart);
            Transport.send(message);
            
        } catch(MessagingException e){
            e.printStackTrace();
            return false;
        }
        return true;
    }
}
lviggiani
  • 5,824
  • 12
  • 56
  • 89
  • Do you mean `sendEmail()`? :) Also, doesn't work. Nothing gets attached. Same result as before: subject, text = fine. attachments = don't exist. – Mark Buffalo Oct 20 '15 at 14:04
  • Yes `EMail.sendEmail()` method, sorry I forgot an "E". I'm using that class in several contexts and send multiple attachments to multiple users with success. Are you sure your attachment files exist? Are you passing full path? – lviggiani Oct 20 '15 at 14:08
  • Yes, I'm even trying `file.getAbsolutePath()`. – Mark Buffalo Oct 20 '15 at 14:22
  • Derp. I forgot to add `message.setContent(multipart);` at the end. +1 Works perfectly, thank you. – Mark Buffalo Oct 20 '15 at 14:25
  • `DataSource datasource = new FileDataSource(file); bodypart.setDataHandler(new DataHandler(datasource));` work for me – hungcuiga1 Jun 13 '21 at 02:15
0

you can create a zip file from your desired folder and then send it as a normal file.

public static void main(String[] args) throws IOException {
String to = "Your desired receiver email address ";


String from = "for example your GMAIL";
//Get the session object  
Properties properties = System.getProperties();  
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.smtp.host", "smtp.gmail.com");
properties.put("mail.smtp.port", "587");
// Get the Session object.
Session session = Session.getInstance(properties,
        new javax.mail.Authenticator() {
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(from, "Insert your password here");
    }
});

try {
    // Create a default MimeMessage object.
    Message message = new MimeMessage(session);
    // Set From: header field of the header.
    message.setFrom(new InternetAddress(from));
    // Set To: header field of the header.
    message.setRecipients(Message.RecipientType.TO,
            InternetAddress.parse(to));
    message.setSubject("Write the subject");
    String Final_ZIP = "C:\\Users\\Your Path\\Zipped.zip";
     String FOLDER_TO_ZIP = "C:\\Users\\The folder path";
        zip(FOLDER_TO_ZIP,Final_ZIP);
    // Create the message part
    BodyPart messageBodyPart = new MimeBodyPart();
    // Now set the actual message
    messageBodyPart.setText("Write your text");

    
    Multipart multipart = new MimeMultipart();
    // Set text message part
    multipart.addBodyPart(messageBodyPart);
    DataSource source = new FileDataSource(Final_ZIP);
    messageBodyPart = new MimeBodyPart();
    messageBodyPart.setDataHandler(new DataHandler(source));
        
    messageBodyPart.setFileName("ZippedFile.zip");
    multipart.addBodyPart(messageBodyPart);
        // Send the complete message parts
    message.setContent(multipart);

    // Send message
    Transport.send(message);

    System.out.println(" Email has been sent successfully....");
    

} catch (MessagingException e) {
    e.printStackTrace();
    throw new RuntimeException(e);
}

}

then the Zip Function is:

 public static void zip( String srcPath,  String zipFilePath) throws IOException {
        Path zipFileCheck = Paths.get(zipFilePath);
        if(Files.exists(zipFileCheck)) { // Attention here it is deleting the old file, if it already exists
            Files.delete(zipFileCheck);
            System.out.println("Deleted");
        }
        Path zipFile = Files.createFile(Paths.get(zipFilePath));

        Path sourceDirPath = Paths.get(srcPath);
        try (ZipOutputStream zipOutputStream = new ZipOutputStream(Files.newOutputStream(zipFile));
             Stream<Path> paths = Files.walk(sourceDirPath)) {
            paths
                    .filter(path -> !Files.isDirectory(path))
                    .forEach(path -> {
                        ZipEntry zipEntry = new ZipEntry(sourceDirPath.relativize(path).toString());
                        try {
                            zipOutputStream.putNextEntry(zipEntry);
                            
                            Files.copy(path, zipOutputStream);
                            zipOutputStream.closeEntry();
                        } catch (IOException e) {
                            System.err.println(e);
                        }
                    });
        }

        System.out.println("Zip is created at : "+zipFile);
    }
    
Shila Mosammami
  • 999
  • 6
  • 20