將 Outlook 連絡人項目附加至Email訊息

本主題描述如何在傳送郵件之前,以程式設計方式將連絡人、行事曆專案或其他電子郵件訊息等 Microsoft Outlook 專案的複本附加至電子郵件訊息。

提供者: Ken Getz、 MCW Technologies、LLC

若要將一或多個檔案或 Outlook 專案附加至郵件訊息,您可以使用代表您傳出郵件之MailItem物件的Attachments屬性,並針對每個附件呼叫Attachments物件的Add (Object、Object、Object、Object) 方法。 Add方法可讓您指定檔案名,以及要如何建立附件的關聯。 若要附加 Outlook 專案,例如本主題範例程式碼中顯示的連絡人項目,請將 Add 方法的Type 參數指定為 Outlook.olAttachmentType.olEmbeddedItem 列舉值。

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

  • Outlook Application物件的參考。

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

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

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

建立新的訊息項目之後,程式碼會迴圈查看所有收件者位址,並將每個位址新增至郵件的 Recipients 集合。 一旦程式碼呼叫Recipients物件的ResolveAll () 方法,就會設定訊息項目的SubjectBody屬性。 接下來,程式碼會建立新的 Outlook ContactItem 物件,並將這個新的連絡人項目新增為郵件訊息的附件,並將 Outlook.olAttachmentType.olEmbeddedItem 值指定為 Add 方法呼叫的參數。 實際傳送電子郵件之前,您必須指定要從中傳送電子郵件訊息的帳戶。 尋找此資訊的其中一個技巧是使用寄件者 SMTP 位址。 函 GetAccountForEmailAddress 式會接受包含寄件者 SMTP 電子郵件地址的字串,並傳回對應 Account 物件的參考。 這個方法會比較寄件者的 SMTP 位址與針對會話設定檔定義的每個已設定電子郵件帳戶的 SmtpAddressapplication.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 元件參考 。 下列程式碼示範如何以程式設計方式將連絡人項目的複本附加至郵件訊息。 為了示範這項功能,請在 Visual Studio 中建立名為 EmbedOutlookItemAddIn 的新受控 Outlook 增益集,並以下列範例程式碼取代 ThisAddIn.vb 或 ThisAddIn.cs 檔案的內容。 修改程式, ThisAddIn_Startup 並適當地更新電子郵件地址。 程式呼叫 SendMailWithAttachments 中包含的 SMTP 位址必須對應至您先前在 Outlook 中設定的其中一個外寄電子郵件帳戶的 SMTP 位址。

using System;
using System.Collections.Generic;
using Outlook = Microsoft.Office.Interop.Outlook;
 
namespace EmbedOutlookItemAddIn
{
    public partial class ThisAddIn
    {
        private void ThisAddIn_Startup(object sender, System.EventArgs e)
        {
            List<string> recipients = new List<string>();
            recipients.Add("john@contoso.com");
            recipients.Add("john@example.com");
 
            // Replace the SMTP address for sending.
            SendMailItem(Application, "Outlook started", "Outlook started at " + 
                DateTime.Now, recipients, "john@contoso.com");
        }
 
        private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
        {
        }
 
        public void SendMailItem(Outlook.Application application, 
            string subject, string body, 
            List<string> recipients, string smtpAddress)
        {
 
            Outlook.MailItem 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())
            {
                // Set the details.
                newMail.Subject = subject;
                newMail.Body = body;
 
                Outlook.ContactItem contact = (Outlook.ContactItem)(application.CreateItem
                    Outlook.OlItemType.olContactItem));
 
                // Create a new contact. Use an existing contact instead, 
                // if you have one to work with.
                contact.FullName = "Kim Abercrombie";
                contact.LastName = "Kim";
                contact.FirstName = "Abercrombie";
                contact.HomeTelephoneNumber = "555-555-1212";
                contact.Save();
 
                newMail.Attachments.Add(contact, Outlook.OlAttachmentType.olEmbeddeditem);
                newMail.SendUsingAccount = GetAccountForEmailAddress(application, smtpAddress);
                newMail.Send();
             }
          }
 
        public 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 recipients As New List(Of String)
        recipients.Add("john@contoso.com")
        recipients.Add("john@example.com")
     
        ' Replace the SMTP address for sending.
        SendMailItem(Application, "Outlook started",
            "Outlook started at " & DateTime.Now, recipients,
            "john@contoso.com")
    End Sub
 
    Private Sub ThisAddIn_Shutdown() Handles Me.Shutdown
 
    End Sub
 
    Private Sub SendMailItem(ByVal application As Outlook.Application, _
        ByVal subject As String, ByVal body As String, ByVal recipients As List(Of String), _
        ByVal smtpAddress As String)
 
        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
          ' Set the details.
          newMail.Subject = subject
          newMail.Body = body
 
          Dim contact As Outlook.ContactItem =_
             DirectCast(application.CreateItem(
             Outlook.OlItemType.olContactItem), Outlook.ContactItem)
 
          ' Create a new contact. Use an existing contact instead, 
          ' if you have one to work with.
          contact.FullName = "Kim Abercrombie"
          contact.LastName = "Kim"
          contact.FirstName = "Abercrombie"
          contact.HomeTelephoneNumber = "555-555-1212"
          contact.Save()
 
          newMail.Attachments.Add(contact, Outlook.OlAttachmentType.olEmbeddeditem)
          newMail.SendUsingAccount = GetAccountForEmailAddress(application, smtpAddress)
          newMail.Send()
        End If
    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郵件的附件

支援和意見反應

有關於 Office VBA 或這份文件的問題或意見反應嗎? 如需取得支援服務並提供意見反應的相關指導,請參閱 Office VBA 支援與意見反應