การเพิ่มไฟล์แนบและข้อความ HTML ไปยังไฟล์ Outlook MSG

Office Automation

โดยใช้วิธีนี้ Microsoft Outlook จำเป็นต้องติดตั้งบนเครื่องที่โค้ด VBA ทำงาน โค้ดตัวอย่างด้านล่างสร้างไฟล์ Outlook MSG พร้อมไฟล์แนบและเนื้อหา 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 for Java

โค้ดส่วนนี้ใช้ไลบรารี Aspose.Email for Java เพื่อสร้างไฟล์ MSG ซึ่งคล้ายกับ ไฟล์ที่สร้างขึ้นข้างต้น, พร้อมไฟล์แนบหลายไฟล์และเนื้อหา HTML เนื่องจาก Aspose.Email for Java เขียนด้วย Java เท่านั้น จึงไม่จำเป็นต้องใช้ COM interop นอกจากนี้ Microsoft Outlook 2003/2007 ไม่จำเป็นต้องติดตั้งบนเครื่อง วิธีที่อธิบายด้านล่างเหมาะสำหรับกรณีที่ไม่ได้ติดตั้ง Microsoft Outlook หรือเมื่อต้องการสร้างไฟล์ MSG บนเซิร์ฟเวอร์

โค้ดตัวอย่างด้านล่างแสดงวิธีทำเช่นเดียวกันใน Java โดยใช้ Aspose.Email for 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());