Share via


Limitar o tamanho de um anexo a uma mensagem de Email do Outlook

Este tópico descreve como você pode criar um suplemento gerenciado para o Outlook que cancela o envio de email se o tamanho total do anexo for maior que um limite fixo.

Fornecido por: Ken Getz, MCW Technologies, LLC

Uma determinada mensagem de email pode conter um ou mais anexos de arquivo e talvez você queira limitar o tamanho total do anexo em mensagens de email enviadas. O código de exemplo neste tópico demonstra como você pode lidar com o evento ItemSend em um suplemento do Outlook e, no manipulador de eventos, cancelar o envio da mensagem de email se o tamanho combinado de todos os anexos for maior que um valor específico (2 MB, neste exemplo).

O evento Outlook ItemSend recebe como seus parâmetros uma referência ao item que está sendo enviado e uma variável booliana que é passada por referência e que permite cancelar a operação de envio. Cabe ao seu próprio código no manipulador de eventos determinar se você deseja cancelar o evento; você o fará definindo o parâmetroCancel como True se desejar cancelar o evento.

Neste exemplo, para determinar se o tamanho total do anexo é maior que um tamanho específico, o código passa por cada anexo na coleção Anexos do item. Para cada item, o código recupera a propriedade Size , resumindo como ela é loops. Se a soma exceder o tamanho da constante maxSize , o código definirá a tooLarge variável como True e sairá do loop. Após o loop, se a tooLarge variável for True, o código alertará o usuário e definirá o parâmetro Cancelar para o manipulador de eventos (que foi passado por referência) para True, fazendo com que o Outlook cancele o envio do item.

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.

You should use the following code samples in the ThisAddIn class of an Outlook add-in (using Office Developer Tools for Visual Studio). The Application object in the code must be a trusted Outlook Application object provided by ThisAddIn.Globals. For more information about using the Outlook PIA to develop managed Outlook solutions, see the Outlook 2013 Primary Interop Assembly Reference on MSDN.

O código a seguir mostra como cancelar o envio de um email se o tamanho total do anexo for maior que o limite especificado. Para demonstrar essa funcionalidade, no Visual Studio, crie um novo suplemento gerenciado do Outlook chamado LimitAttachmentSizeAddIn. Substitua o código em ThisAddIn.cs ou ThisAddIn.vb pelo código de exemplo mostrado aqui.

using Outlook = Microsoft.Office.Interop.Outlook;
 
namespace LimitAttachmentSizeAddIn
{
    public partial class ThisAddIn
    {
        private void ThisAddIn_Startup(object sender, System.EventArgs e)
        {
          Application.ItemSend +=new Outlook.ApplicationEvents_11_ItemSendEventHandler(Application_ItemSend);
        }
 
        private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
        {
        }
 
        void Application_ItemSend(object Item, ref bool Cancel)
        {
            // Specify the maximum size for the attachments. For this example,
            // the maximum size is 2 MB.
            const int maxSize = 2 * 1024 * 1000;
            bool tooLarge = false;
 
            Outlook.MailItem mailItem = Item as Outlook.MailItem;
            if (mailItem != null)
            {
                var attachments = mailItem.Attachments;
                double totalSize = 0;
                foreach (Outlook.Attachment attachment in attachments)
                {
                    totalSize += attachment.Size;
                    if (totalSize > maxSize)
                    {
                        tooLarge = true;
                        break;
                    }
                }
            }
            if (tooLarge)
            {
                // If the sum of the attachment sizes is too large, alert the user
                // and cancel the send.
                System.Windows.Forms.MessageBox.Show(
                    "The total attachment size is too large. Sending canceled.", 
                    "Outlook Add-In");
                Cancel = true;
            }
        }
 
        #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
 
    End Sub
 
    Private Sub ThisAddIn_Shutdown() Handles Me.Shutdown
 
    End Sub
 
    Private Sub Application_ItemSend(ByVal Item As Object, ByRef Cancel As Boolean) Handles Application.ItemSend
        ' Specify the maximum size for the attachments. For this example,
        ' the maximum size is 2 MB.
        Const maxSize As Integer = 2 * 1024 * 1000
        Dim tooLarge As Boolean = False
 
        Dim mailItem As Outlook.MailItem = TryCast(Item, Outlook.MailItem)
        If mailItem IsNot Nothing Then
            Dim attachments = mailItem.Attachments
            Dim totalSize As Double = 0
 
            For Each attachment As Outlook.Attachment In attachments
                totalSize += attachment.Size
                If totalSize > maxSize Then
                    tooLarge = True
                    Exit For
                End If
            Next attachment
        End If
 
        If tooLarge Then
            ' If the sum of the attachment sizes is too large, alert the user
            ' and cancel the send.
            System.Windows.Forms.MessageBox.Show(
                "The total attachment size is too large. Sending canceled.",
                "Outlook Add-In")
            Cancel = True
        End If
    End Sub
End Class

Confira também

Anexar um arquivo a um item de emailAnexar um item de contato do Outlook a uma mensagem de EmailModificar um anexo de uma mensagem do Outlook Email

Suporte e comentários

Tem dúvidas ou quer enviar comentários sobre o VBA para Office ou sobre esta documentação? Confira Suporte e comentários sobre o VBA para Office a fim de obter orientação sobre as maneiras pelas quais você pode receber suporte e fornecer comentários.