Java 邮件,发送多个附件不起作用
2022-09-03 13:35:53
我在互联网上看了很多条目,但没有运气。
这是我的代码:
import java.io.IOException;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
public class MailTest
{
public static void main(String[] args) throws AddressException, MessagingException, IOException
{
String host = "***";
String from = "b";
String to = "***";
// Get system properties
Properties props = System.getProperties();
// Setup mail server
props.put("mail.smtp.host", host);
// Get session
Session session = Session.getDefaultInstance(props, null);
// Define message
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject("Hello JavaMail");
message.setText("Welcome to JavaMail");
// Handle attachment 1
MimeBodyPart messageBodyPart1 = new MimeBodyPart();
messageBodyPart1.attachFile("c:/Temp/a.txt");
// Handle attachment 2
MimeBodyPart messageBodyPart2 = new MimeBodyPart();
messageBodyPart2.attachFile("c:/Temp/b.txt");
MimeMultipart multipart = new MimeMultipart("related");
multipart.addBodyPart(messageBodyPart1);
multipart.addBodyPart(messageBodyPart2);
message.setContent(multipart);
// Send message
Transport.send(message);
}
}
结果是我只得到附加的第一个文件。
- 我尝试多次调用 attachFile 方法,但随后它只应用最后一个附件
- 我尝试在addBodyPart上玩索引:没有帮助
我检查了普通消息,我看到其中具有相同标识符的其他文件,并且由于某种原因未在附件中列出。
任何帮助将不胜感激,戴夫