我正在使用 JavaMail API 在我的 Java Web 应用程序中发送电子邮件。我的用例是向不同的收件人发送多封包含用户特定内容的电子邮件。内容包括pdf文件附件。我想做如下代码,
Map<Long, ByteArrayOutputStream> pdffiles = new HashMap<Long, ByteArrayOutputStream>();
Map<Long, String> contentMap = new HashMap<Long,String>();
start of loop
{
String userId = //uniqId;
ByteArrayOutputStream outFile= new ByteArrayOutputStream();
outFile = // statement to invoke a method to create the customer
specific pdf file
String fileName = "Invoice_<company_name>"+".pdf";
MimeBodyPart pdfBodyPart = new MimeBodyPart();
pdffiles.put(userId, outFile);
String content = //Some user specific content loaded here.
contentMap.put(userId, content);
}
Session session = Session.getInstance(props, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
List<MimeMessage> msgList= new ArrayList<MimeMessage>();
for(Long userid : contentMap.keySet()){
String content = contentMap.get();
String contentType ="text/html;charset=UTF-8";
MimeMessage msg = new MimeMessage(session);
ByteArrayOutputStream outFile = // get the pdf file from map using the userid as key
byte[] bytes = outFile.toByteArray();
DataSource dataSource = new ByteArrayDataSource(bytes,
"application/pdf");
pdfBodyPart.setDataHandler(new DataHandler(dataSource));
Multipart multipart = new MimeMultipart();
try {
//adding the passed multipart content to the mail that to send
as an inline attachment.
messageBodyPart.setContent(content, contentType);
multipart.addBodyPart(messageBodyPart);
multipart.addBodyPart(pdfBodyPart);
msg.setContent(multipart);
// have to add this 'msg' Object in List.
InternetAddress[] addressTo = null;
try {
addressTo = InternetAddress.parse(eo.getTo());
msg.setRecipients(Message.RecipientType.TO, addressTo);
} catch (AddressException e) {
// excpetion handled here
} catch (MessagingException e) {
// excpetion handled here
}
}catch (MessagingException e) {
} catch (Exception e) {//expetion handled here
}
}
Transport transport = null;
try {
transport = session.getTransport("smtp");
} catch (NoSuchProviderException e) {
//exception handled here
}
try {
transport.connect();
for(MimeMessage msg : msgList){
transport.sendMessage(msg, msg.getAllRecipients());
}
transport.close();
}catch (Exception ex) {
//exception handled here
}
我的问题是, HashMap 是否接受 ByteArrayOutputStream 类实例作为值?如果是这样,如何使用 key 从 Map 获取它?
ArrayList 是否接受保存 MimeMessage 对象?如果是这样, 如果 MimeMessage 的 Bodypart 中有大文件怎么办?当将大文件作为列表保存在内存中时会发生什么?
最佳答案
是的,HashMap
和 ArrayList
可以存储 Object
的任何子类型,包括 ByteArrayOutputStream
或 MimeMessage
作为值。
也许可以回答您的部分困惑:这些数据结构并不将实际对象存储在它们“内部”;相反,HashMap
和 ArrayList
存储对必须已存在于内存中的对象的引用。
因此,只要您有足够的内存来创建ByteArrayOutputStream
,用于存储对其引用的额外内存就不太可能成为问题。
关于java - Map 可以将 java 类 ByteArrayoutputstream 作为值吗? List 可以保存 javax.mail.MimeMessage 对象吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55794751/