Outlook MSG ファイルへの添付ファイルと HTML テキストの追加

Office Automation

この方法を使用するには、VBA コードが実行されるマシンに Microsoft Outlook がインストールされている必要があります。以下のコードスニペットは、添付ファイルと HTML 本文を持つ Outlook MSG ファイルを作成します。

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 インターロップは不要です。また、Microsoft Outlook 2003/2007 をマシンにインストールする必要もありません。以下に示す方法は、Microsoft Outlook がインストールされていない場合やサーバー上で MSG ファイルを生成したい場合に適しています。

以下のコードスニペットは、Aspose.Email for Java を使用して 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());