Click here to Skip to main content
6,595,854 members and growing! (19,606 online)
Email Password   helpLost your password?
General Programming » Internet / Network » MAPI     Intermediate License: The Code Project Open License (CPOL)

Programmatically adding attachments to emails

By David M Brooks

A technique for programmatically adding attachments to emails.
C++Win2K, WinXP, Visual Studio, MFC, WTL, Dev
Posted:18 Jan 2006
Views:108,685
Bookmarked:35 times
Announcements
Loading...
 
Search    
Advanced Search
Add to IE Search
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
15 votes for this article.
Popularity: 5.48 Rating: 4.66 out of 5
1 vote, 6.7%
1

2

3
3 votes, 20.0%
4
11 votes, 73.3%
5

Introduction

Having read Stephane Rodriguez's excellent and rather clever solution to programmatically adding attachments to Outlook emails, I realized how subtly useful this functionality was. Many was the time I have needed a way to send an application's document to another user. Obviously, it could be done by writing your own dialogs that mimic the mail client dialogs, but you have to hook up the address book and so on. It's far better to exploit the existing mail client software installed on the PC. I needed exactly this for an application so it could have File->Send To functionality - obviously, it needs attachments to work.

SendTo or MailTo

Stephane's article makes the perfectly valid point that using the SendTo approach is functionally better than using the mailto trick. Another compelling reason for not using mailto is it doesn't support attachments. The RFC mailto protocol is simple and doesn't specify attachments.

However, you commonly see code trying to use mailto like this:

mailto:shiver@metimbers.com?Subject=Ahoy there 
  shipmate&Body=Here's the shipping 
  manifest&Attach="D:\manifest.doc"

It probably won't attach the document because you are at the liberty of the email client to implement the mailto protocol and include parsing for the attachment clause. You may not know what mail client is installed on the PC, so it may not always work - Outlook certainly doesn't support attachments using mailto.

So what's the best (and easiest) way to do it

Stephane's solution is neat. It simulates a drag 'n drop into Outlook by using an unpublished mail helper COM object. However, by using unpublished functionality, you are at the mercy of the vendor (in this case Microsoft) changing things! And this is what has happened. The drag drop code works with no problem at all when using Outlook 2002/2003 on Win2K, but throws a 'Privileged exception' when running on XP. The presumption is there are permission issues with this combination of OS and the version of Outlook.

I needed a mail client version independent solution that supported attachments, so I chose to investigate MAPI. As it turns out, the answer is pretty simple, which is wrapped up in the CSendFileTo class.

#ifndef __SENDFILETO_H__
#define __SENDFILETO_H__

#include <mapi.h>


class CSendFileTo
{
public:
    bool SendMail(HWND hWndParent, 
         CString const &strAttachmentFileName, 
         CString const &strSubject=_T(""))
    {
        // The attachment must exist as a file on the system

        // or MAPISendMail will fail, so......

        if (strAttachmentFileName.IsEmpty())
            return false;

        // You may want to remove this check, but if a valid

        // HWND is passed in, the mail dialog will be made

        // modal to it's parent.

        if (!hWndParent || !::IsWindow(hWndParent))
            return false;

        HINSTANCE hMAPI = ::LoadLibraryA(_T("MAPI32.DLL"));
        if (!hMAPI)
            return false;

        // Grab the exported entry point for the MAPISendMail function

        ULONG (PASCAL *SendMail)(ULONG, ULONG_PTR, 
                      MapiMessage*, FLAGS, ULONG);
        (FARPROC&)SendMail = GetProcAddress(hMAPI, 
                              _T("MAPISendMail"));

        if (!SendMail)
            return false;

        TCHAR szFileName[_MAX_PATH];
        TCHAR szPath[_MAX_PATH];
        TCHAR szSubject[_MAX_PATH];
        ::StrCpy(szFileName, strAttachmentFileName.GetString());
        ::StrCpy(szPath, strAttachmentFileName.GetString());
        ::StrCpy(szSubject, strSubject.GetString());

        MapiFileDesc fileDesc;
        ::ZeroMemory(&fileDesc, sizeof(fileDesc));
        fileDesc.nPosition = (ULONG)-1;
        fileDesc.lpszPathName = szPath;
        fileDesc.lpszFileName = szFileName;

        MapiMessage message;
        ::ZeroMemory(&message, sizeof(message));
        message.lpszSubject = szSubject;
        message.nFileCount = 1;
        message.lpFiles = &fileDesc;

        // Ok to send

        int nError = SendMail(0, (ULONG_PTR)hWndParent, 
               &message, MAPI_LOGON_UI|MAPI_DIALOG, 0);

        if (nError != SUCCESS_SUCCESS && 
            nError != MAPI_USER_ABORT && 
            nError != MAPI_E_LOGIN_FAILURE)
              return false;

        return true;
    }
};

#endif

Example use

This nugatory code fragment shows how easy it is to use.

#include "SendFileTo.h"

...
...

CSendFileTo sendTo;
sendTo.(m_hWnd, _T("c://documents//menu.doc"), 
                _T("Here's the lunch menu"));

...
...

This is all straightforward, but there are a few points to note.

  • If the attachment doesn't exist as a file on the file system, the call to MAPISendMail will fail with MAPI_E_ATTACHMENT_NOT_FOUND. Hence the check at the start of the SendMail call.
  • By passing the parent HWND to the MAPISendMail function, the email client is supposed to make the send mail dialog modal to the given HWND. You may want to remove this modalness(?) and simply use HWND_DESKTOP.
  • When the MAPISendMail call is made, it doesn't send the mail, it just pops up the email client dialog with the optional subject line set and the attachment attached.
  • This code was written to compile and work with WTL (it rocks), but will work equally well using MFC.

I've successfully tested this with Outlook 2002 and 2003 on Win2K and XP. I'd be interested in hearing if it works with other mail clients I don't have access to - Eudora etc.

This class could probably do with some more error checking but I'll leave that as an exercise for the reader.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

David M Brooks


Member
When Dave isn't trying to play drums, fly helicopters or race cars, he can be found trying to be a Consultant at www.candelamedia.co.uk He must try harder!

You can read Dave's ramblings in his blog Aliens Ate My GUI
Occupation: Web Developer
Location: United Kingdom United Kingdom

Other popular Internet / Network articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 25 of 56 (Total in Forum: 56) (Refresh)FirstPrevNext
GeneralWARNING = THIS CODE PROBABLY UNSAFE Pinmembersashasawchai23:21 1 Dec '08  
GeneralRe: WARNING = THIS CODE PROBABLY UNSAFE PinmemberDavid M Brooks6:14 27 Aug '09  
Generalto send more than 1 mail address [modified] PinmemberArielR11:08 2 Jul '08  
Generalwhat for ? Pinmemberkilt20:59 25 Jun '08  
QuestionLotus Notes ignores lpszFileName Pinmembertiggerlily0:08 30 Nov '07  
Generalwhy it saves the draft into inbox folder? Pinmemberxuxiaohui23:37 7 Nov '07  
QuestionNewbie problem - can't compile (get errors in mapi.h) Pinmembercgalpin5:59 1 Nov '07  
AnswerRe: Newbie problem - can't compile (get errors in mapi.h) PinmemberVarchas R S0:03 5 Nov '07  
GeneralRe: Newbie problem - can't compile (get errors in mapi.h) Pinmembercgalpin8:42 6 Nov '07  
QuestionSending html formatted email Pinmemberkryzzozz7810:09 10 Oct '07  
GeneralRe: Sending html formatted email PinmemberMember 21634705:56 31 Mar '08  
Generalprofile problem with MAPI Pinmemberrob01030:48 30 Jul '07  
GeneralRe: profile problem with MAPI PinmemberBhushanKalse21:28 27 Aug '07  
Generalthanks! Pinmembercronky7821:17 12 Jul '07  
Generalsending problem Pinmember133mmxtr3:20 11 Jun '07  
QuestionWCHAR version of Mapi32.dll ?? [modified] Pinmemberajitatif angajetor3:49 24 Jan '07  
AnswerRe: WCHAR version of Mapi32.dll ?? Pinmemberhannahb4:22 21 Mar '07  
GeneralRe: WCHAR version of Mapi32.dll ?? Pinmemberajitatif angajetor7:21 27 Mar '07  
Generalwants demo & source Pinmembershital_harode@rediffmail.com0:24 18 Nov '06  
GeneralRe: wants demo & source Pinmemberprathuraj0:10 6 Jun '07  
GeneralAnyone know how to do this with C# Pinmemberc-a-b-9:49 24 Aug '06  
GeneralRe: Anyone know how to do this with C# [modified] PinmemberDavid Broooks5:01 12 Dec '06  
GeneralRe: Anyone know how to do this with C# Pinmemberc-a-b-11:31 12 Dec '06  
GeneralRe: Anyone know how to do this with C# PinmemberSriharsha R2:19 19 Jan '07  
AnswerRe: Anyone know how to do this with C# Pinmembergoondoo2711:52 7 Feb '07  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 18 Jan 2006
Editor: Smitha Vijayan
Copyright 2006 by David M Brooks
Everything else Copyright © CodeProject, 1999-2009
Web15 | Advertise on the Code Project