Thêm Tệp đính kèm và Văn bản HTML vào tệp Outlook MSG
Mẹo di chuyển của chúng tôi cho thấy cách các sản phẩm Aspose có thể được sử dụng để cải thiện ứng dụng của bạn và giải phóng bạn khỏi phụ thuộc vào tự động hoá truyền thống.
Mẹo di chuyển này cho thấy cách tạo tệp MSG với nội dung định dạng HTML và thêm nhiều tệp đính kèm vào nó:
- Một đoạn mã VBA sử dụng Tự động Hoá Microsoft Office để tạo tệp MSG có các tệp đính kèm và nội dung HTML.
- Cũng đạt được tương tự bằng cách sử dụng Aspose.Email cho Java.
Tự động Hoá Office
Khi sử dụng phương pháp này, Microsoft Outlook phải được cài đặt trên máy mà mã VBA chạy. Đoạn mã dưới đây tạo tệp Outlook MSG có các tệp đính kèm và nội dung HTML.
VBA
' Create an object of type Outlook.Application
Set objOutlookApplication = CreateObject("Outlook.Application")
' Create an object of type olMailItem
Set objMsg = objOutlookApplication.CreateItem(olMailItem)
' Set properties of the message file e.g. subject, body and to address
' Set subject
objMsg.Subject = "This MSG file is created using Office Automation."
' Set to (recipient) address
objMsg.To = "to@domain.com"
' Set body of the email message
objMsg.HTMLBody = "<html><p>This MSG file is created using VBA code.</p>"
' Add attachments to the message
objMsg.Attachments.Add "C:\test.bmp"
objMsg.Attachments.Add "C:\test2.jpg"
' Save as Outlook MSG file
objMsg.SaveAs ("c:\testvba.msg")
' Open the MSG file
objMsg.Display
Aspose.Email cho Java
Đoạn mã dưới đây sử dụng thư viện Aspose.Email cho Java để tạo tệp MSG, tương tự như cái đã tạo ở trên, với nhiều tệp đính kèm và nội dung HTML. Vì Aspose.Email cho Java được viết hoàn toàn bằng Java, không cần COM interop. Ngoài ra, không cần cài đặt Microsoft Outlook 2003/2007 trên máy. Phương pháp dưới đây phù hợp khi Microsoft Outlook không được cài đặt hoặc khi bạn muốn tạo tệp MSG trên máy chủ.
Các đoạn mã dưới đây cho thấy cách thực hiện cùng tác vụ bằng Java sử dụng Aspose.Email cho Java:
// Create an instance of type MailMessage
MailMessage msg = new MailMessage();
// Set properties of message like subject, to and HTML body
// Set subject
msg.setSubject("This MSG file is created using Aspose.Email for .NET");
// Set from (sender) address
msg.setSender(new MailAddress("from@domain.com", "From Name"));
// Set to (recipient) address and name
msg.getTo().addItem(new MailAddress("to@domain.com", "To Name"));
// Set HTML body of the email message
msg.setHtmlBody("<html><p>This MSG file is created using Java code.</p>"
+ "<p>Microsoft Outlook does not need to be installed on the machine running this code.</p>"
+ "<p>This method is suitable for creating MSG files on the server side.</html>");
// Add attachments to the message file
msg.getAttachments().addItem(new Attachment("C:\\test.bmp"));
msg.getAttachments().addItem(new Attachment("C:\\test2.jpg"));
// Save as Outlook MSG file
String strSaveFile = "C:\\TestAspose.msg";
msg.save(strSaveFile, SaveOptions.getDefaultMsgUnicode());