Welcome to MSDN Blogs Sign in | Join | Help

How to remove attachments from outlook (2007) emails easily

I receive often emails with big attachment that fill my inbox space very quickly.
On the other side, I usually like both to remove these attach and keep the email to preserve the thread for future use. Outlook 2007 don't have this feature so I wrote the following VBA function I added to a button on my client that resolve easily this task.
 
image
 
image
 
TIP: You can select more message at once too. This is useful if you want to clear a big number of messages you already have archived.
 
Hope this helps!
Nicola

Note: I already developed this VBA for outlook 2003, but Outlook 2007 requires some small update. following code should work.
 
UPDATE (09/06/09): Thanks to John Harvey and Patrick Philippot now the procedure save attachments in a specific folder and make good use of outlook memory:-)
UPDATE (22/10/09): Thanks to Steve Evans now it shows a link to folder where the attaches are saved
 
 
' by Nicola Delfino
'       30-03-2005: First version
'       26-11-2006: Updated for Outlook 2007
'       28-11-2006: Updated with notes from rgreg
'       09-06-2009: Saves the file(s) to a folder location (thanks to John Harvey and Patrick Philippot)
'                   Memory problem with many attach to remove (FIXED) (thanks to John Harvey and Patrick Philippot)
'       22-10-2009: Now it uses default "My document folder"
'                   added HTML and link to saved files (thanks to Steve Evans)
'
'   based on code found at on http://www.outlookcode.com/
'
' Setup and instructions
' (1) Digitally sign VBA project
'          start->office->Microsoft office tools->digital certificates for VBA
'          create a certificate
' (2) sign the code
'          from Outlook -> menu -> Tools -> Macros -> Visual Basic Editor (VBA)
'          project 1 -> Microsoft Office Outlook -> ThisOutlookSession (double ckick)
'          * paste this source code *
'          from Microsoft Visual Basic -> menu -> Tools -> digital signature -> (choose certificate previously created)
' (3) add icon on toolbar
'          from outlook
'          tools->customize (select "Commands" TAB)
'                add icon on toolbar
'                [rearrange commands] to change icon and name on toolbar
' (4) be sure that tools->macros->security
'               on "thrusted publishers" "trust all installed add-ins and templates" is checked
'
'
 
Private Declare Function SHGetFolderPath Lib "shell32.dll" Alias "SHGetFolderPathA" ( _
    ByVal HWnd As Long, ByVal csidl As Long, ByVal hToken As Long, ByVal dwFlags As Long, ByVal pszPath As String) As Long
 
Private Const MAX_PATH = 260&
 
Public Sub StripAttachments()
    Dim ilocation As String
    Dim objOL As Outlook.Application
    Dim objMsg As Object
    Dim objAttachments As Outlook.Attachments
    Dim objSelection As Outlook.Selection
    Dim i As Long
    Dim lngCount As Long
    Dim strFile As String
    Dim strFolder As String
 
    Dim result
    
    'Put in the folder location you want to save attachments to
    ilocation = GetSpecialFolder(&H5) & "\Removed Attachs\" ' CSIDL_MY_DOCUMENTS As Long = &H5"
    On Error Resume Next
    
    result = MsgBox("Do you want to remove attachments from selected email(s)?", vbYesNo + vbQuestion)
    If result = vbNo Then
        Exit Sub
    End If
    
    ' Instantiate an Outlook Application object.
    ' Set objOL = CreateObject("Outlook.Application")
    Set objOL = Application
    ' Get the collection of selected objects.
    Set objSelection = objOL.ActiveExplorer.Selection
 
    ' Check each selected item for attachments.
    ' If attachments exist, save them to the Temp
    ' folder and strip them from the item.
    For Each objMsg In objSelection
        ' This code only strips attachments from mail items.
        If objMsg.Class = olMail Then
            ' Get the Attachments collection of the item.
            Set objAttachments = objMsg.Attachments
            lngCount = objAttachments.Count
            If lngCount > 0 Then
                ' We need to use a count down loop for
                ' removing items from a collection. Otherwise,
                ' the loop counter gets confused and only every
                ' other item is removed.
                strFile = ""
                For i = lngCount To 1 Step -1
                    ' Save attachment before deleting from item.
                    ' Get the file name.
                    
                    Dim strHTML As String
                    strHTML = "<li><a href=" & Chr(34) & "file:" & ilocation & objAttachments.Item(i).FileName & Chr(34) & ">" & objAttachments.Item(i).FileName & "</a><br>" & vbCrLf
                                        
                    strFile = strFile & strHTML
           
                    
                    ' Save the attachment as a file.
                    objAttachments.Item(i).SaveAsFile (ilocation & objAttachments.Item(i))
                    
                    ' Save the attachment as a file.
                    objAttachments.Item(i).Delete
                Next i
                
                strFile = "Attachment removed from the message and backup-ed to[<a href='" & ilocation & "'>" & ilocation & "</a>]:<br><ul>" & strFile & "</ul><hr><br><br>" & vbCrLf & vbCrLf
                
                Dim objDoc As Object
                Dim objInsp As Outlook.Inspector
                Set objInsp = objMsg.GetInspector
                Set objDoc = objInsp.WordEditor
                
                
                objDoc.Characters(1).InsertBefore strFile
                objMsg.HTMLBody = strFile + objMsg.HTMLBody
                
                Set objInsp = Nothing
                Set objDoc = Nothing
            End If
            strFile = strFile & vbCrLf & vbCrLf
            objMsg.Save
        End If
    Next
 
ExitSub:
    Set objAttachments = Nothing
    Set objMsg = Nothing
    Set objSelection = Nothing
    Set objOL = Nothing
End Sub
Public Function GetSpecialFolder(FolderCSIDL As Long) As String
    Dim HWnd As Long
    Dim Path As String
    Dim Res As Long
    Dim ErrNumber As Long
    Dim ErrText As String
    Path = String$(MAX_PATH, vbNullChar)
    
    ''''''''''''''''''''''''''''''''''''''''''''
    ' get the folder name
    ''''''''''''''''''''''''''''''''''''''''''''
    Res = SHGetFolderPath(HWnd:=0&, _
                            csidl:=FolderCSIDL, _
                            hToken:=0&, _
                            dwFlags:=0&, _
                            pszPath:=Path)
    Select Case Res
        Case S_OK
            Path = TrimToNull(Text:=Path)
            GetSpecialFolder = Path
        Case S_FALSE
            MsgBox "The folder code is valid but the folder does not exist."
            GetSpecialFolder = vbNullString
        Case E_INVALIDARG
            MsgBox "The value of FolderCSIDL is not valid."
            GetSpecialFolder = vbNullString
        Case Else
            ErrNumber = Err.LastDllError
            ErrText = "ERROR!"
            MsgBox "An error occurred." & vbCrLf & _
                "System Error: " & CStr(ErrNumber) & vbCrLf & _
                "Description:  " & ErrText
    End Select
End Function
Public Function TrimToNull(Text As String) As String
    Dim N As Long
    N = InStr(1, Text, vbNullChar)
    If N Then
        TrimToNull = Left(Text, N - 1)
    Else
        TrimToNull = Text
    End If
End Function
Posted by NicolD | 7 Comments

NicolTIP#007: What to do when you no longer can run macros in Outlook 2007

I am quoting information from [http://blog.tjitjing.com/index.php/2007/03/things-i-can-and-cannot-get-to-work-in.html] because I tumbled in this issue and forgot to "just" restart Outlook :^)

Whenever I went in to Tools - Macro - Macros, selected my macro and hit run I would end up in the Visual Basic editor with an error message saying “The macros in this project are disabled. Please refer to the online help or documentation of the host application to determine how to enable macros.”
I went in to Tools - Macro - Macro Security and first changed from the default “Warnings for signed macros; all unsigned macros are disabled” to “Warnings for all macros” and finally to “No security check for macros” but I still could not get the macros to run.
In spite of a lot of Googling I found nothing. Then I realized I hadn’t tried trick no 1 in the book: Restart Outlook. And of course that was the solution
(Note to Microsoft: Please add a “Outlook needs to be restarted” message. Note to myself: Don’t be so stupid next time around)

A good thing in Outlook 2007 is that I no longer get the “A program is trying to access e-mail addresses you have stored in Outlook. Do you want to allow this? … Allow for x minutes”. I assume they have gotten rid of this annoying message and replaced with some security feature that does not require user intervention.

Posted by NicolD | 0 Comments

NicolTIP#006: how to show previous and next item using LINQ

I had a table on SQL 2005 I am accessing it via LINQ. I had to select an item via a “where” condition (see below).

var item = (from snap in adc.Snapshots
      where snap.file == image
      select snap).First();

The problem was that I needed to identify the previous item and the next item too because we had to show them on a web page. Talking with some collgues of mine we found the following way that looks quite smart:

var previous = adc.Snapshots.OrderByDescending(s => s.InsertDateTime).Where(s => string.Compare(s.file, image) < 0).FirstOrDefault();
var item = adc.Snapshots.OrderBy(s => s.InsertDateTime).Where(s => s.file == image).SingleOrDefault();
var next = adc.Snapshots.OrderBy(s => s.InsertDateTime).Where(s => string.Compare(s.file, image) > 0).FirstOrDefault();

Posted by NicolD | 0 Comments
Filed under: ,

NicolTIP#005: How to show the same content in two ore more positions using master page in ASP.NET

To write a web site and give to the entire site a coherent “look” with ASP.NET and master pages is very easy and productive. In brief, into the master page you need to put “placeholders” using the tag <asp:ContentPlaceHolder/> and into the content page, you can map real content with contenplaces (more information).

Sometime can be required to put the same content in more places, an example is the “title” field that you could put both in the header\title field and into a H1 tag into the body.

This means, starting from the following content page:

<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPages/Root.Master" AutoEventWireup="true" %>
<asp:Content ID="Content1" ContentPlaceHolderID="Title" runat="server">This is my title</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MyContent" runat="server">This is my content</asp:Content>

To obtain the following html output:

<html>
<head>
    <title>This is my title</title>
</head>
<body>
<h1>This is my title</h1>
This is my content
</body>
</html>

The easy way I found is shown in the following master page:

<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Root.master.cs" Inherits="NicolD.MasterPages.Root" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title><asp:ContentPlaceHolder id="Title" runat="server"></asp:ContentPlaceHolder></title>
</head>
<body>
<h1><span id="TitleOnPage" runat="server"></span></h1>
<asp:ContentPlaceHolder id="MyContent" runat="server" Visible="false"></asp:ContentPlaceHolder>
</body>
</html>

the true secret is in the master page’s code behind:-), where I filled “TitleOnPage” with “Title” place holder content.

public partial class Root : System.Web.UI.MasterPage
{
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);

        this.Page.LoadComplete += new EventHandler(Page_LoadComplete);
    }

    private void Page_LoadComplete(object sender, EventArgs e)
    {
        LiteralControl lc = (LiteralControl)Title.Controls[0];
        TitleOnPage.InnerText = lc.Text;

    }

}

NicolTIP#004: seven new keyboard shortcuts for Window 7

I love keyboard shortcuts and W7 add some new really cool…

Managing Your Windows. Windows 7 simplifies document and program management by allowing you to “dock” a window or manipulate its size with one mouse maneuver or a simple keystroke. To dock your window on one half of the screen, drag it to the left or right and it will change its size to fit that half of the screen. To manipulate the vertical size of a window, you can drag the window to the top to maximize it, or double-click the window’s top or bottom border to maximize it vertically while keeping the same width.

You can also perform all of these functions with keystrokes:

  • Windos key+Left Arrow and Windos key+Right Arrow dock to half the screen
  • Windos key+Up Arrow and Windos key+ Down Arrow maximize and minimize
  • Windos key+Shift+Up Arrow and Windos key+Shift+Down Arrow maximize

and restore vertical size.

 

Multi-Monitor Window Management. Windows 7 makes using multiple monitors as convenient as it should be. When you’re working multi-monitor, use the keyboard shortcuts Windos key+Shift+Left Arrow and Windos key+Shift+Right Arrow to move windows from one monitor to another. The rearranged window will keep its relative position to the top-left origin on the new monitor.

 

Project Your Display With Ease. Plugging in a projector and projecting your display is a snap with the Windows 7 driver display utility, displayswitch.exe. Simply hit Windos key+P and you’ll be rewarded with the following easy-to-navigate pop-up window. By hitting your arrow keys (or Windos key+P) you can switch through multiple display settings, such as “clone”, “extend” or “external only”.

 

Live Clutter-Free. We live with enough clutter in our lives. Windows 7 gets rid of all the superfluous windows behind your active window. Just hit Windos key+Home to minimize all inactive windows. To restore the windows when you’d like them, just press:

  • Windos key+Home again

 

Help the Help Desk Help You. Solving problems unique to a machine can be an arduous task for both the end-user and the help desk. That’s why Windows 7 introduces the Problem Steps Recorder, a screen-capture tool that allows the end-user to record the problems they’re having step-by-step. It’s as simple as hitting “record” then adding in comments as needed. A HTML-based file is converted to a .ZIP folder, which is easily passed on to the help desk. The program is accessible from the Control Panel under “Record steps to reproduce a problem” or run psr.exe from Explorer.

 

Aero Peek Your Desktop. A lesser-known versatile tool on the taskbar introduced with Windows 7 is the Windows® Aero® feature, “Aero Peek” – the small rectangle in the lower right hand corner. It allows you to peek at any of the icons or gadgets on your desktop. The keyboard shortcut Windos key+Space performs the same function.

 

Shuffling Through Program Windows. If you’re running a number of files from the same program, such as multiple documents in Microsoft Word, Windows 7 allows you to switch through these windows with ease. Simply hold down the Ctrl key while repeatedly clicking the icon from the taskbar. Each click will change the window to the next in the sequence, in the order that you opened them.

Posted by NicolD | 1 Comments

NicolTIP#003: How to install Windows SharePoint Services 3.0 Tools - Visual Studio 2008 Extensions, Version 1.2 on Windows Vista

If you try to install Windows SharePoint Services 3.0 Tools - Visual Studio 2008 Extensions, Version 1.2 on Windows Vista, you will get an error message telling you that you have to install Windows SharePoint Services 3.0 in order to install the tools. Windows SharePoint Services 3.0 (WSS 3.0) doesn't support non Windows Servers OS, so it's not possible to install WSS 3.0 on Windows Vista, which means you will not be able to install VS 2008 Extensions on your development machine.

This happens because setup just checks on the registry the presence of a specific key. To avoid this behavior and install these extensions on Vista (but should work on XP as well) just write the following key on your machine registry:

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Shared Tools\Web Server Extensions\12.0]
"Sharepoint"="Installed"

NicolTIP#002: Create a manifest.xml extracting content type(s) and columns from a site using Sharepoint Designer

Step to extract a content type and columns to CAML (XML)

  • Create you content type and columns in the web UI.
  • Create a list/library item using you new content type.
  • Load up Sharepoint Designer to the site where you created you item.
  • From the File menu, click Export -> Personal Web Package.
  • In the export web package window select the list/library where your create the item using the new content type and click add.
  • Save the package to your local drive.
  • Next browse to where you saved the file and rename it from .fwp to .cab.
  • Extract manifest.xml to your local drive.
  • Load the file up in your favourite XML viewer (might take a second or two it can be a large file).
  • Navigate to the UserLists/Field node (Solution/UserLists/Fields).
  • within this node look for your field, you will be able to see the CAML that describes your field.

NicolTIP#001: edit easily your machine's HOST file

Edit the HOST file in Vista is difficult than ever, thanks to UAC. If you’re a geek that changes HOST file daily this can be a bit frustrating. I circumnavigated the difficulty with a shortcut.

  1. Right click on the folder you want to place the hyperlink (i.e. desktop) and select “new->Shortcut”
  2. As location of the item type: notepad.exe C:\Windows\System32\drivers\etc\hosts
  3. As Shortcut name type “Edit HOST file (as administrator)”
  4. right click on the new shortcut just created and select “properties”
  5. Select “Advanced”
  6. Select “Run as Administrator”

Now, if you need to edit the HOST file (and folder where you put the shortcut is indexed by vista search) just click on start button and type “edit host”

Edit Machine HOST file

Posted by NicolD | 1 Comments
Filed under: , , ,

Chrome OS?

Yesterday evening I had the opportunity to read in detail the document that describe Google Chrome features. Interesting is that if I read "O.S." each time in the document appairs the word "browser" all the document continues to have sense. Very, very interesting:-)

Posted by NicolD | 0 Comments
Filed under:

Polipo Matico

PolipoMatico is a Windows Vista sidebar gadget that allows to retrieve and show italia traffic infos from octotelematics web site (www.octotelematics.it)

image

Why
Because traffic in Italy is a serious topic, and because we like to be at home, at the end of the day, with less stress as possible:-)

Usage
Just install the gadget, and add it to the sidebar. Main commands:

  • Mouse wheel: zoom in and out
  • Use the orange icon to select "rotate" or "drag" mode
  • to rotate or drag, just click and drag the image
  • double click: reset image position


Supported Areas
Roma - GRA (Grande Raccordo Anulare)

 

Download it from CodePlex: Polipo Matico

How to provide a context sentitive help to your WPF application

I found the following (and very) interesting post where is well described how to provide your windows presentation fundation client application with a context sensitive help. Chek it out!

http://blogs.msdn.com/mikehillberg/archive/2007/07/26/a-context-sensitive-help-provider-in-wpf.aspx

Posted by NicolD | 0 Comments

Win32 Application contextmenu piloting (UI Automation)

I just developed a PoC where I demonstrated to my customer how is feasible to integrate and manipulate a Win32 application (Remedy Client in my case) into a CCF (Customer Care Framework) client application.

In this context I had some problem in piloting context menu. the couple of link below give much information.

My main takeways:

  • standard context menu class name is "#32768"
  • usually context menu send a WM_COMMAND message to the application window with an ID that trigger the operation
  • when you successfully selected the context menu window (you have the HWND):
    • you can choose the menu item via WM_KEYDOWN/VK_DOWN messages
    • you can activate the menu item via a WM_KEYDOWN/VK_ENTER message

Links that saved my day:

Posted by NicolD | 0 Comments

WPF: How to embed an Icon in an Assembly

You can easily integrate resources in your Windows Presentation Foundation application by using the WPF designer for Visual Studio and "pack:" URI scheme provided by XAML to reference resources in your application's XAML.

for more information have a look to MSDN article.

Posted by NicolD | 0 Comments
Filed under:

How to access Hyper-V (RC0) machine (workgroup) from Vista SP1 joined to a domain

Step 1: Install this update to enable remote management of a Windows Server 2008 computer running the Hyper-V RC0 role

Step 2: If the server is either a member of WORKGROUP or is in a different domain that is untrusted by the client, then the connection from the server to the client used to return asynchronous results is created as an Anonymous connection. An anonymous connection fails with either the 0x80070005 error or the 0x8007000e error unless Anonymous connections are given the DCOM Remote Access permission on the client. The following steps grant DCOM remote access permissions from the server to the client in this scenario.

    1. Click Start, click Run, type DCOMCNFG, and then click OK.
    2. In the Component Services dialog box, expand Component Services, expand Computers, and then right-click My Computer and click Properties.
    3. In the My Computer Properties dialog box, click the COM Security tab.
    4. Under Access Permissions, click Edit Limits.
    5. In the Access Permission dialog box, select ANONYMOUS LOGON name in the Group or user names box. In the Allow column under Permissions for User, select Remote Access, and then click OK.

Step 3: from command prompt execute the following command:

  • cmdkey /add:yourhyper-vmachine /user:hyper-vdomani\administrator /pass:hyper-vadministratorpassword

in example:

  • cmdkey /add:srv04 /user:srv04\administrator /pass:123.password.123
NOTE: use netbios name (i.e. SRV04) and not FQDN name (i.e. SRV04.myintranet.local)
Posted by NicolD | 1 Comments
Filed under: ,
More Posts Next page »
 
Page view tracker