我这里可以发送邮件与多个附件:如何使用多个附件发送邮件,在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