共用方式為


將檔案附加至 Outlook Email訊息

本主題描述如何以程式設計方式將一或多個檔案附加至 Microsoft Outlook 中的外寄電子郵件訊息。

提供者: Ken Getz、 MCW Technologies、LLC

附件的物件模型支援

在 Outlook 中,MailItem物件的Attachments屬性支援將一或多個檔案附加至電子郵件訊息。 若要在傳送專案之前將一或多個檔案附加至訊息項目,您可以針對每個附件檔案呼叫Attachments物件的 Add (Object、Object、Object) 方法。 Add方法可讓您使用OlAttachmentType列舉 (指定源參數) 的檔案名,以及 (Type 參數) 的附件類型。 針對檔案系統中的檔案,請將Type 參數指定為 Outlook.olAttachmentType.olByValue 列舉值。

注意 自 Microsoft Office Outlook 2007 起,您一律會使用此值在檔案系統中附加檔案的複本;不再支援 Outlook.olAttachmentType.olByReference

此外,當您傳送 RTF) (RTF 格式的電子郵件時,您也可以在呼叫 Add 方法時指定另外兩個選擇性參數:Position 和DisplayName。 Position 參數可讓您指定電子郵件內附件應該出現的位置。 針對Position 參數使用下列其中一個值:

  • 值 0 會隱藏電子郵件本文內的附件。

  • 值 1 會將附件放在第一個字元之前。

  • 大於電子郵件專案本文中字元數的數位,會將附件放在本文的結尾。

對於 RTF 電子郵件訊息,您也可以指定 DisplayName 參數,以提供附件之訊息本文中顯示的名稱。 對於純文字或 HTML 電子郵件訊息,附件只會顯示檔案名。

以檔案作為附件傳送訊息

SendEmailWithAttachments本主題稍後程式碼範例中的範例程式接受下列專案:

  • Outlook Application物件的參考。

  • 包含訊息主旨和本文的字串。

  • 字串的一般清單,其中包含郵件收件者的 SMTP 地址清單。

  • 包含寄件者 SMTP 位址的字串。

  • 字串的泛型清單,其中包含要附加之檔案的路徑。

建立新的電子郵件專案之後,程式碼會將每個收件者新增至訊息項目的 Recipients 集合屬性。 一旦程式碼呼叫 ResolveAll () 方法之後,它會先設定訊息項目的 SubjectBody 屬性,再迴圈查看所提供附件路徑清單中的每個專案,並將每個專案新增至訊息項目的 Attachments 屬性。

實際傳送電子郵件之前,您必須指定要從中傳送電子郵件訊息的帳戶。 尋找此資訊的其中一個技巧是使用寄件者 SMTP 位址。 函 GetAccountForEmailAddress 式會接受包含寄件者 SMTP 電子郵件地址的字串,並傳回對應 Account 物件的參考。 這個方法會比較寄件者的 SMTP 位址與針對會話設定檔定義的每個已設定電子郵件帳戶的 SmtpAddress 屬性。 application.Session.Accounts 會傳回目前設定檔的 Accounts 集合、所有帳戶的追蹤資訊,包括 Exchange、IMAP 和 POP3 帳戶,每個帳戶都可以與不同的傳遞存放區相關聯。 具有關聯SmtpAddress屬性值且符合寄件者 SMTP 位址的Account物件是用來傳送電子郵件訊息的帳戶。

識別適當的帳戶之後,程式碼會完成,方法是將訊息項目的 SendUsingAccount 屬性設定為該 Account 物件,然後呼叫 Send () 方法。

The following managed code samples are written in C# and Visual Basic. To run a .NET Framework managed code sample that needs to call into a Component Object Model (COM), you must use an interop assembly that defines and maps managed interfaces to the COM objects in the object model type library. For Outlook, you can use Visual Studio and the Outlook Primary Interop Assembly (PIA). Before you run managed code samples for Outlook 2013, ensure that you have installed the Outlook 2013 PIA and have added a reference to the Microsoft Outlook 15.0 Object Library component in Visual Studio. 您應該使用 Office Developer Tools for Visual Studio) ,在 Outlook 增益集 (類別中使用下列程式碼 ThisAddIn 範例。 程式碼中的Application物件必須是 所 ThisAddIn.Globals 提供的受信任 Outlook應用程式物件。 如需使用 Outlook PIA 開發受控 Outlook 解決方案的詳細資訊,請參 閱 MSDN 上的歡迎使用 Outlook 主要 Interop 元件參考

下列程式碼示範如何以程式設計方式將檔案附加至 Outlook 中的外寄電子郵件訊息。 為了示範這項功能,請在 Visual Studio 中建立名為 AttachFileAddIn 的新受控 Outlook 增益集,並以下列範例程式碼取代 ThisAddIn.vb 或 ThisAddIn.cs 檔案的內容。 修改程式以 ThisAddIn_Startup 包含檔案系統中檔案的參考,並適當地更新電子郵件地址。 程式呼叫 SendMailWithAttachments 中包含的 SMTP 位址必須對應至您先前在 Outlook 中設定的其中一個外寄電子郵件帳戶的 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 支援與意見反應