Outlook 電子メール メッセージにファイルを添付する

このトピックでは、プログラムによって Microsoft Outlook で送信電子メール メッセージに 1 つまたは複数のファイルを添付する方法について説明します。

提供者: Ken Getz、 MCW Technologies, LLC

添付ファイルのオブジェクト モデルのサポート

Outlook では、MailItem オブジェクトの Attachments プロパティでは、1 つ以上のファイルをメール メッセージに添付できます。 メール アイテムを送信する前にそのアイテムに 1 つ以上のファイルを添付するには、 各添付ファイルに対して、 Attachments オブジェクトの Add(Object, Object, Object, Object) メソッドを呼び出します。 Add メソッドを使用すると、OlAttachmentType 列挙型を使用して、ファイル名 (theSource パラメーター) と添付ファイルの種類 (theType パラメーター) を指定できます。 ファイル システム内のファイルの場合は、 Outlook.olAttachmentType.olByValue 列挙値としてType パラメーターを指定します。

メモ Microsoft Office Outlook 2007 以降では、常にこの値を使用してファイル システム内のファイルのコピーを添付します。 Outlook.olAttachmentType.olByReference はサポートされなくなりました。

さらに、リッチ テキスト形式 (RTF) でメールを送信する場合は、 Add メソッドを呼び出すときに、他の 2 つの省略可能なパラメーター Position とDisplayName を指定することもできます。 Position パラメーターを使用すると、添付ファイルを表示する電子メール内の位置を指定できます。 Position パラメーターには、次のいずれかの値を使用します。

  • 値 0 は、電子メールの本文内の添付ファイルを隠します。

  • 値 1 は、添付ファイルを最初の文字の前に配置します。

  • 電子メール アイテムの本文の文字数より大きい数字を指定すると、本文テキストの最後に添付ファイルを配置します。

RTF メール メッセージの場合は、添付ファイルのメッセージ本文に表示される名前を指定する DisplayName パラメーターを指定することもできます。 プレーン テキストまたは HTML メール メッセージの場合、添付ファイルにはファイルの名前のみが表示されます。

添付ファイルとしてファイルを指定したメッセージを送信する

SendEmailWithAttachmentsこのトピックの後のコード例のサンプル プロシージャでは、次の内容を受け入れます。

  • Outlook Application オブジェクトへの参照。

  • メッセージの件名および本文を含む文字列。

  • メッセージの受信者の SMTP アドレスの一覧が含まれる文字列のリスト。

  • 送信者の SMTP アドレスを含む文字列。

  • 添付するファイルのパスが含まれる文字列のリスト。

新しいメール アイテムを作成した後、コードは各受信者をメール アイテムの Recipients コレクション プロパティに追加します。 コードが ResolveAll() メソッドを呼び出すと、メール アイテムの Subject プロパティおよび Body プロパティが設定され、次いで添付ファイルのパスが記されている指定されたリストの各アイテムをループして、メール アイテムの Attachments プロパティにそれぞれを追加します。

実際に電子メールを送信する前に、電子メール メッセージの送信元となるアカウントを指定する必要があります。 この情報を見つける方法の 1 つに、送信者の SMTP アドレスを使用する方法があります。 関数は GetAccountForEmailAddress 、送信者の SMTP メール アドレスを含む文字列を受け取り、対応する Account オブジェクトの参照を返します。 このメソッドは、送信者の SMTP アドレスを、セッションのプロファイルに対して定義されている構成済みの電子メール アカウントごとに SmtpAddress プロパティと比較します。 application.Session.Accounts は、現在のプロファイルの Accounts コレクションを返します。Exchange、IMAP、POP3 アカウントを含むすべてのアカウントの追跡情報は、それぞれ異なる配信ストアに関連付けることができます。 送信者の SMTP アドレスに一致する SmtpAddress プロパティが関連付けられている Account オブジェクトは、電子メール メッセージを送信するのに使用するアカウントです。

適切なアカウントを識別した後、メール アイテムの SendUsingAccount プロパティを その Account オブジェクトに設定し、 Send() メソッドを呼び出して、コードが完了します。

The following managed code samples are written in C# and Visual Basic. コンポーネント オブジェクト モデル (COM) に呼び出す必要がある .NET Framework マネージ コード サンプルを実行するには、マネージ インターフェイスを定義し、オブジェクト モデル タイプ ライブラリの COM オブジェクトにマップする相互運用機能アセンブリを使用する必要があります。 Outlook の場合、Visual Studio および Outlook プライマリ相互運用機能アセンブリ (PIA) を使用できます。 Outlook 2013 用のマネージ コード サンプルを実行する前に、Outlook 2013 PIA をインストールしており、Visual Studio で Microsoft Outlook 15.0 オブジェクト ライブラリ コンポーネントへの参照を追加していることを確認してください。 Outlook アドインのクラスでは ThisAddIn 、次のコード サンプルを使用する必要があります (Office Developer Tools for Visual Studio を使用)。 コードの Application オブジェクトは で提供された、信頼済み Outlook ThisAddIn.Globals オブジェクトである必要があります。 Outlook PIA を使用してマネージド Outlook ソリューションを開発する方法の詳細については、MSDN の 「Outlook プライマリ相互運用機能アセンブリ リファレンスへようこそ」を参照 してください。

次のコードは、Outlook で送信電子メール メッセージにプログラムでファイルを添付する方法を示しています。 この機能を示すために、Visual Studio で、 という名前 AttachFileAddInの新しいマネージド Outlook アドインを作成し、ThisAddIn.vb または ThisAddIn.cs ファイルの内容を、ここに示すコード例に置き換えます。 ファイル システムに ThisAddIn_Startup ファイルへの参照を含める手順を変更し、メール アドレスを適切に更新します。 SendMailWithAttachments プロシージャへの呼び出しに含まれる SMTP アドレスは、以前 Outlook で構成した送信電子メール アカウントの 1 つの SMTP アドレスに対応していなければなりません。

using System.Collections.Generic;
using Outlook = Microsoft.Office.Interop.Outlook;
 
namespace AttachFileAddIn
{
    public partial class ThisAddIn
    {
        private void ThisAddIn_Startup(object sender, System.EventArgs e)
        {
            List<string> attachments = new List<string>();
            attachments.Add("c:\\somefile.txt");
 
            List<string> recipients = new List<string>();
            recipients.Add("john@contoso.com");
            recipients.Add("john@example.com");
            SendEmailWithAttachments(Application, "Test", "Body", recipients, "john@example.com", 
              attachments);
        }
 
        private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
        {
        }
 
        private void SendEmailWithAttachments(Outlook.Application application, 
            string subject, string body, List<string> recipients, 
            string smtpAddress, List<string> attachments)
        {
 
            // Create a new MailItem and set the To, Subject, and Body properties.
            var newMail = application.CreateItem(Outlook.OlItemType.olMailItem) as Outlook.MailItem;
 
            // Set up all the recipients.
            foreach (var recipient in recipients)
            {
                newMail.Recipients.Add(recipient);
            }
            if (newMail.Recipients.ResolveAll())
            {
                newMail.Subject = subject;
                newMail.Body = body;
                foreach (string attachment in attachments)
                {
                    newMail.Attachments.Add(attachment, Outlook.OlAttachmentType.olByValue);
                }
            }
 
            // Retrieve the account that has the specific SMTP address.
            Outlook.Account account = GetAccountForEmailAddress(application, smtpAddress);
            // Use this account to send the email.
            newMail.SendUsingAccount = account;
            newMail.Send();
        }
 
        private Outlook.Account GetAccountForEmailAddress(Outlook.Application application, 
            string smtpAddress)
        {
 
            // Loop over the Accounts collection of the current Outlook session.
            Outlook.Accounts accounts = application.Session.Accounts;
            foreach (Outlook.Account account in accounts)
            {
                // When the email address matches, return the account.
                if (account.SmtpAddress == smtpAddress)
                {
                    return account;
                }
            }
            // If you get here, no matching account was found.
            throw new System.Exception(string.Format("No Account with SmtpAddress: {0} exists!", 
                smtpAddress));
        }
 
        #region VSTO generated code
 
        /// <summary>
        /// Required method for Designer support - don't modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InternalStartup()
        {
            this.Startup += new System.EventHandler(ThisAddIn_Startup);
            this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown);
        }
        
        #endregion
    }
}
Public Class ThisAddIn
 
    Private Sub ThisAddIn_Startup() Handles Me.Startup
        Dim attachments As New List(Of String)
        attachments.Add("c:\somefile.txt")
 
        Dim recipients As New List(Of String)
        recipients.Add("john@contoso.com")
        recipients.Add("john@example.com")
        SendEmailWithAttachments(Application, "Test", "Body", recipients, "john@contoso.com", attachments)
    End Sub
 
    Private Sub ThisAddIn_Shutdown() Handles Me.Shutdown
 
    End Sub
 
    Private Sub SendEmailWithAttachments(ByVal application As Outlook.Application, _
        ByVal subject As String, ByVal body As String,
        ByVal recipients As List(Of String),
        ByVal smtpAddress As String,
        ByVal attachments As List(Of String))
 
        ' Create a new MailItem and set the To, Subject, and Body properties.
        Dim newMail As Outlook.MailItem =
            DirectCast(application.CreateItem(Outlook.OlItemType.olMailItem), 
            Outlook.MailItem)
 
        ' Set up all the recipients.
        For Each recipient In recipients
            newMail.Recipients.Add(recipient)
        Next
        If newMail.Recipients.ResolveAll() Then
            newMail.Subject = subject
            newMail.Body = body
            For Each attachment As String In attachments
                newMail.Attachments.Add(attachment, Outlook.OlAttachmentType.olByValue)
            Next
        End If
 
        ' Retrieve the account that has the specific SMTP address.
        Dim account As Outlook.Account = GetAccountForEmailAddress(application, smtpAddress)
        ' Use this account to send the email.
        newMail.SendUsingAccount = account
        newMail.Send()
    End Sub
 
   
    Private Function GetAccountForEmailAddress(
        ByVal application As Outlook.Application,
        ByVal smtpAddress As String) As Outlook.Account
 
        ' Loop over the Accounts collection of the current Outlook session.
        Dim accounts As Outlook.Accounts = application.Session.Accounts
        For Each account In accounts
            ' When the email address matches, return the account.
            If account.SmtpAddress = smtpAddress Then
                Return account
            End If
        Next
        ' If you get here, no matching account was found.
        Throw New System.Exception(
            String.Format("No Account with SmtpAddress: {0} exists!", smtpAddress))
    End Function
End Class

関連項目

Outlook 連絡先アイテムを Email メッセージに添付する Outlook Email メッセージへの添付ファイルのサイズを制限する Outlook Emailメッセージの添付ファイルを変更する

サポートとフィードバック

Office VBA またはこの説明書に関するご質問やフィードバックがありますか? サポートの受け方およびフィードバックをお寄せいただく方法のガイダンスについては、Office VBA のサポートおよびフィードバックを参照してください。