Click here to Skip to main content
Click here to Skip to main content

Programmatically adding attachments to emails

By , 18 Jan 2006
 

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
Web Developer
United Kingdom United Kingdom
When Dave isn't trying to play drums, fly helicopters or race cars, he can be found trying to be CTO at www.eventility.co.uk He must try harder!
 
You can read Dave's ramblings in his blog Aliens Ate My GUI
 
Or, if you can be bothered, he twitters on BoomerDave

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionNice, works now with wxwidgets as wellmemberMember 90858329-Jul-12 8:12 
i just changed a bit, so it works with wxWidgets, thanks for this easy solution.
Questionsendto with attachment solutionmembermanywebbs9-Sep-11 18:14 
how do I implement this solution in outlook?, I downloaded the code but do not know where to add it or place it. Many thanks
GeneralMy vote of 5memberitz_faraz5-May-11 19:31 
Excellent rating goes to David Brooks for converting this into C# in the comments section below!
GeneralI hate to nag but this code sample is bad...memberdc_200025-Apr-11 17:46 
I appreciate the author taking time to post this code sample (and I understand that it is somewhat old), but there are several major issues with it:
 
1. Even though the author attempted to put Unicode specific types (TCHAR instead of char, etc.), he clearly didn't try compiling it under Unicode. Within that specification the code has a bunch of holes... so be aware!
 
2. The code has an obvious memory leak when the mapi library is loaded with LoadLibrary() call but never unloaded.
 
3. Also why posting what is already available in description in the download link? Why not create a small compilable project?
QuestionCan I use this solution for my problem....memberdkperez21-Jan-10 12:16 
Tabular html form into which a user enters 1 or more titles and matching file spec. In this case the filespec is the full path, filename, and extension on the user's local system... SO, for an image called sunrise.jpg what they'd have to enter is something like
d:\images\morning\sunrise.jpg.
 
When done the user hits SUBMIT and everything gets sent to php and stored.
 
I need them to email the files they've entered to an address, and I'd prefer to do this from the client so I don't have to upload a bunch of large image files to the server.
 
So, I'd like to use some form of client emailer, preferably one that makes use of the mail engine on the user's PC so they don't have to wait while a server "mail" synchronously processes and sends a bunch of images (seems very slow)......
 
If it WILL work in this case, can someone provide very specific information about where the code has to go and how to use whatever does the call in html...
 
thanks.
GeneralWARNING = THIS CODE PROBABLY UNSAFEmembersashasawchai1-Dec-08 22:21 
I highly recommend reading this post on MSDN:
 
http://blogs.msdn.com/mstehle/archive/2007/10/03/fyi-why-are-mapi-and-cdo-1-21-not-supported-in-managed-net-code.aspx[^]
 
My reading of it is that the code presented here - while it will work, is probably unsafe and will probably introduce memory leaks and other potential problems into your application. WTF | :WTF:
 
Thanks be to Microsoft. Mad | :mad:
 
You have been warned...
GeneralRe: WARNING = THIS CODE PROBABLY UNSAFEmemberDavid M Brooks27-Aug-09 5:14 
It depends on how you clean things up when you've finished with them.
 
To counter the argument, I've used a variation of this code in a corporate application with a user base of over 1600. It's been running for over 3 years with no problems yet.
 
Dave
Generalto send more than 1 mail address [modified]memberArielR2-Jul-08 10:08 
what must to modify at the code to send more than one mail address. Thanks
 
modified on Wednesday, July 2, 2008 5:32 PM

GeneralRe: to send more than 1 mail addressmemberpine_le11-Apr-10 4:28 
recipient[0].ulRecipClass = MAPI_TO;
recipient[0].lpszName = ArrayEmail.GetBuffer(0);
recipient[0].lpszAddress = "";
recipient[0].ulEIDSize = 0;
recipient[0].lpEntryID = NULL;
here, ArrayEmail = "user1@test.com; user2@test.com; ...."
Questionwhat for ?memberkilt25-Jun-08 19:59 
An "article" which just copies MSDN code or hundreds of Usenet codes posted for 13 years ?
Is it a joke ?
Pathetic Frown | :-(
QuestionLotus Notes ignores lpszFileNamemembertiggerlily29-Nov-07 23:08 
Lotus Notes (v7 and v8) ignores lpszFileName when attaching a file with Simple MAPI. Instead, Notes uses the filename from lpszPathName as the displayable attachment filename seen by the recipients.
 
Caveat: If a single file is attached with lpszPathName ending in ".tmp", Notes does use lpszFileName as displayed name. But, attempting to attach more than one file with name ending in ".tmp" causes "Notes MailMan error" to pop up. In order to attach multiple files, each lpszPathName must end in other than ".tmp", e.g., ".temp" or ".jpg". But, Notes disregards lpszFileName unless lpszPathName ends with ".tmp".
 
Outlook correctly honors lpszFileName.
 
As a workaround for Notes, I could use the desired displayable name as the filename portion of lpszPathName. For example, my app could download URL to \docs and settings\joe\Local Settings\Temp\Harry Potter.txt. But, that doesn't work when lpszPathName contains special unicode characters.
 
Does anyone have a solution?

 

http://msdn2.microsoft.com/en-us/library/ms530443.aspx says:
 
lpszPathName
 
Pointer to the fully qualified path of the attached file. This path should include the disk drive letter and directory name.
 
lpszFileName
 
Pointer to the attachment filename seen by the recipient, which may differ from the filename in the lpszPathName member if temporary files are being used. If the lpszFileName member is empty or NULL, the filename from lpszPathName is used.

Questionwhy it saves the draft into inbox folder?memberxuxiaohui7-Nov-07 22:37 
Thanks your code!
 
But I have the same question about "why it saves the draft into inbox folder?"
 
Thank you!
 
Peter
 
-----------------------------------------------------------
Two Questions? Sstar 23:13 1 May '06

2. When the Mail dialog pops up, instead of sending it, if I click on the 'save' button, found that the mail is saved into my INBOX folder. By right, the mail should be saved into the DRAFT folder, shouldn't it? Is there any option that we could set somewhere to correct this problem when using the MAPI_SENDMAIL function? I am using Ms Outlook 2003.





QuestionNewbie problem - can't compile (get errors in mapi.h)membercgalpin1-Nov-07 4:59 
Sorry for the Newbie question, but I have tried to make a simple test of this using both a console application project and a windows application project in Visual Studio 2005 with no luck. I'm not sure what headers to include to make this work, but both projects fail compiling mapi.h (I get 198 errors - first few shown below).
 
thanks
charles
 
Error 1 error C2143: syntax error : missing ';' before '*' C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\include\mapi.h 43
Error 2 error C4430: missing type specifier - int assumed. Note: C++ does not support default-int C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\include\mapi.h 43
Error 3 error C2146: syntax error : missing ';' before identifier 'LHANDLE' C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\include\mapi.h 48
Error 4 error C4430: missing type specifier - int assumed. Note: C++ does not support default-int C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\include\mapi.h 48
Error 5 error C4430: missing type specifier - int assumed. Note: C++ does not support default-int C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\include\mapi.h 48
Error 6 error C2143: syntax error : missing ';' before '*' C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\include\mapi.h 48
 
and so on
AnswerRe: Newbie problem - can't compile (get errors in mapi.h)memberVarchas R S4-Nov-07 23:03 
Same problem with me too!!!! Frown | :(
GeneralRe: Newbie problem - can't compile (get errors in mapi.h)membercgalpin6-Nov-07 7:42 
I did figure out I need ATL/WTL (it was even mentioned in the original post) but still get various errors I can't resolve. Would someone mind making a quick project that compiles for this so we can see how to satisfy the dependencies?
QuestionSending html formatted emailmemberkryzzozz7810-Oct-07 9:09 
Has anyone sent an html formatted email?
 
I have this:
 
MapiMessage Msg;
 
Msg.lpszNoteText = szBody; // body
 
//If I sent text in lpszNoteText, then email format will be plain text
//If I sent lpsZNoteText empty, then email format will be html
 
So, I want to send a link in the body, something like:
 
<a href:"http://www.codeproject.com">Link to codeproject</a>
 
Can anyone help me on this. Any advice would be greatly appreciated.
 
Thanks.
GeneralRe: Sending html formatted emailmemberMember 216347031-Mar-08 4:56 
I have the same problem!
Generalprofile problem with MAPImemberrob010329-Jul-07 23:48 
this code works great !!! thaaanksBig Grin | :-D
But i 've one problem
We run our solution on a CITRIX server and
so i've another profile then the profile on my local workstation.
 
so everytime i send an email a dialog appears where i
should coose the profile.
 
How can i change the profile name or set the default profile name
 
Maybe someone can give me an example ? Pleeaasee !!
 
I don't know how to do
 
greets Robert
GeneralRe: profile problem with MAPImemberBhushanKalse27-Aug-07 20:28 
Have a look at this, it might help you:
http://support.microsoft.com/kb/180233
Generalthanks!membercronky7812-Jul-07 20:17 
this really helped
Generalsending problemmember133mmxtr11-Jun-07 2:20 
When my outlook is off, MAPISendMail does not work properly. When i call MAPISendMail, the new mail dialog is shown, subject, to and attachment parts are filled. I click send button and the new mail window terminates. But the mail is not sent until i click send-receive button on outlook. With mailto call, the mail is sent directly without clicking send-receive button. But mailto call does not support attachments.
QuestionWCHAR version of Mapi32.dll ?? [modified]memberajitatif angajetor24-Jan-07 2:49 
thanks for the code,it was more than a bunch of help.
but my platform sdk (Win2K3 R2) has the Mapi structures defined using LPSTR,rather than LPTSTR,which gives me trouble especially about non-english characters in the message.
 
i hopelessly tried changing the header file but as expected without result.
does anyone have any idea about this matter?
AnswerRe: WCHAR version of Mapi32.dll ??memberhannahb21-Mar-07 3:22 
Here is a UNICODE only version. I didn't bother setting up for TCHAR template types.
 

#ifndef __SENDFILETO_H__
#define __SENDFILETO_H__
 
#include <mapi.h>
#include
 
class CSendFileTo
{
public:
bool SendMail(HWND hWndParent, CString const &strAttachmentFileName, CString const &strSubject=_T(""))
{
if (strAttachmentFileName.IsEmpty())
return false;
 
if (!hWndParent || !::IsWindow(hWndParent))
return false;
 
HINSTANCE hMAPI = ::LoadLibrary(_T("MAPI32.DLL"));
if (!hMAPI)
return false;
 
ULONG (PASCAL *SendMail)(ULONG, ULONG_PTR, MapiMessage*, FLAGS, ULONG);
(FARPROC&)SendMail = GetProcAddress(hMAPI, "MAPISendMail");
 
if (!SendMail)
return false;
 
char szFileName[_MAX_PATH];
char szPath[_MAX_PATH];
char szSubject[_MAX_PATH];

USES_CONVERSION;
 
::strcpy(szFileName, W2A(strAttachmentFileName.GetString()));
::strcpy(szPath, W2A(strAttachmentFileName.GetString()));
::strcpy(szSubject, W2A(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;
 
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
GeneralRe: WCHAR version of Mapi32.dll ??memberajitatif angajetor27-Mar-07 6:21 
yes this seems to handle the WCHAR characters.
 
but the problem for using USES_CONVERSION macros is they tend to change the non-english characters to the english ones. like "ı" to "i" and "ğ" to "g".
 
so i think i'll need a win32 api that directly supports WCHAR, which i think is not available currently.
Generalwants demo & sourcemembershital_harode@rediffmail.com17-Nov-06 23:24 
Plz send me the source & demo
as early as possible
 
Thank u.
 
Shital
 
dfgsd

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130617.1 | Last Updated 18 Jan 2006
Article Copyright 2006 by David M Brooks
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid