简体   繁体   English

Java:如何将多个文件附加到电子邮件?

[英]Java: How do I attach multiple files to an email?

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.我什至尝试创建一个名为childPartMultipart并通过.setParent()将其分配给mp ,但这也不起作用。

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?如何通过 Java 正确发送多个附件?

This is my own email utility class, check if that the sendMail method works for you这是我自己的电子邮件实用程序类,检查sendMail方法是否适合您

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

you can create a zip file from your desired folder and then send it as a normal file.您可以从所需的文件夹创建一个 zip 文件,然后将其作为普通文件发送。

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:那么 Zip 函数是:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM