我正在使用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类实例作为值?如果可以,如何使用密钥从地图上获取它?
ArrayList是否接受以保存MimeMessage对象?如果是这样的话, 如果MimeMessage的Bodyparts中有大文件怎么办?将大型文件保存为列表时会发生什么?
答案 0 :(得分:0)
是的,HashMap
和ArrayList
可以存储Object
的任何子类型,包括ByteArrayOutputStream
或MimeMessage
作为值。
也许可以回答部分困惑:这些数据结构不会将实际对象存储在其内部。相反,HashMap
和ArrayList
将引用存储到内存中必须已经存在的对象。
只要您有足够的内存来创建 ByteArrayOutputStream
,存储引用的额外内存就不太可能成为问题。