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

3

我有一个在应用程序启动时创建的文件列表,我想通过电子邮件发送这些文件。邮件确实发送了,但是它们没有任何附件。

以下是代码:

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

没有任何错误、警告或其他提示。我甚至尝试创建一个名为childPartMultipart,并通过.setParent()将其分配给mp,但这也没有起作用。
我是这样分配附件的:
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);

我应该如何在Java中正确地发送多个附件?


1
问题只出现在多个附件上吗?也就是说,当您仅附加一个单独的附件时,它可以正常工作吗? - RealSkeptic
似乎存在问题。我想这可能与我的权限有关? - Mark Buffalo
1
不,实际上,现在我看了一下,你只需要使用“==”比较字符串。所以它无法识别你的文件是否以“ext”结尾。 - RealSkeptic
哦,哇,现在那真是贫民区啊。为什么,为什么?哈哈。谢谢,伙计。我有点新手Java,所以那让我感到意外。 - Mark Buffalo
我猜测 setText 覆盖了你的多部分内容。 - Joshua
显示剩余2条评论
2个回答

4

这是我的自定义电子邮件工具类,请检查sendEmail方法是否适用于您的需求。

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

你是不是指的 sendEmail() 函数? :) 另外,它不起作用。没有任何附件被添加。和之前一样的结果:主题、文本没问题,但附件不存在。 - Mark Buffalo
是的,EMail.sendEmail() 方法,抱歉我忘记了一个“E”。我在多个上下文中使用该类,并成功地向多个用户发送多个附件。您确定您的附件文件存在吗?您是否传递了完整路径? - lviggiani
是的,我甚至尝试了 file.getAbsolutePath() - Mark Buffalo
笨蛋,我忘记在结尾处添加 message.setContent(multipart);。+1 完美解决了,谢谢。 - Mark Buffalo
DataSource datasource = new FileDataSource(file); bodypart.setDataHandler(new DataHandler(datasource)); 对我有效。 - hungcuiga1

0

您可以从所需的文件夹创建一个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);
}

}

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接