我这里可以发送带有多个附件的邮件:

Properties props = System.getProperties();
String host = "smtp.gmail.com";
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.user", from);
props.put("mail.smtp.password", pass);
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");

Session session = Session.getDefaultInstance(props);
MimeMessage message = new MimeMessage(session);
Multipart multipart = new MimeMultipart();

// creates body part for the message
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(message, "text/html");

//set message body
BodyPart msgBodyPart = new MimeBodyPart();
msgBodyPart.setText(body);
multipart.addBodyPart(msgBodyPart);
msgBodyPart = new MimeBodyPart();

//attach file
DataSource source = new FileDataSource(attachFile);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(attachFile);
multipart.addBodyPart(messageBodyPart);

//attach file 2
source = new FileDataSource(attachFile2);
BodyPart messageBodyPart2 = new MimeBodyPart();
messageBodyPart2.setDataHandler(new DataHandler(source));
messageBodyPart2.setFileName(attachFile2);
multipart.addBodyPart(messageBodyPart2);

try {
    message.setFrom(new InternetAddress(from));
    InternetAddress[] toAddress = new InternetAddress[to.length];

      // To get the array of addresses
    for( int i = 0; i < to.length; i++ ) {
        toAddress[i] = new InternetAddress(to[i]);
    }

    for( int i = 0; i < toAddress.length; i++) {
        message.addRecipient(Message.RecipientType.TO, toAddress[i]);
    }
} catch (MessagingException ex) {
    ex.printStackTrace();
}

message.setSubject(subject);
message.setContent(multipart);
Transport transport = session.getTransport("smtp");
transport.connect(host, from, pass);
transport.sendMessage(message, message.getAllRecipients());
transport.close();

但问题是如何添加多个附件?我不知道我是否可以声明许多变量或将其放在数组中。该代码只能包含 2 个附件,如果在每次发送的电子邮件中包含 5 个或任何一个。

最佳答案

创建一个名为 attachFile 之类的简单方法,它以 FileMultipartMimeBodyPart 作为参数...

public void attachFile(File file, Multipart multipart, MimeBodyPart messageBodyPart) {
    DataSource source = new FileDataSource(file);
    messageBodyPart.setDataHandler(new DataHandler(source));
    messageBodyPart.setFileName(file.getName());
    multipart.addBodyPart(messageBodyPart);
}

根据需要随时调用它
File attachFiles[] = ...

if (attachFiles > 0) {
    //attach file
    attachFile(attachFiles[0], multipart, messageBodyPart);
    if (attachFiles > 1) {
        for (int index = 1; index < attachFiles.length; index++) {
            attachFile(attachFiles[0], multipart, new MimeBodyPart());
        }
    }
}

举个例子

10-08 09:05