我這裏可以發送郵件與多個附件:如何使用多個附件發送郵件,在java中
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個或任何附件。
這裏是一個重擊出去的想法。創建一個名爲'attach'的方法,它將'File'和'Multipart'作爲參數。你可以多次調用它,看看會發生什麼:) – MadProgrammer 2015-02-24 03:06:46
你知道Java是如何工作的嗎? (具體來說,變量,對象和數組是如何工作的)。如果你這樣做,應該很容易看到如何附加一組文件。 – immibis 2015-02-24 03:11:37