ShellExecute() allows me to perform simple shell tasks, allowing the system to take care of opening or printing files. I want to take a similar approach to sending an email attachment programmatically.
I don't want to manipulate Outlook directly, since I don't want to assume which email client the user uses by default. I don't want to send the email directly, as I want the user to have the opportunity to write the email body using their preferred client. Thus, I really want to accomplish exactly what Windows Explorer does when I right click a file and select Send To -> Mail Recipient.
I'm looking for a C++ solution.
You can use a standard "mailto:" command in windows shell. It will run the default mail client.
This is my MAPI solution:
#include <tchar.h>
#include <windows.h>
#include <mapi.h>
#include <mapix.h>
int _tmain( int argc, wchar_t *argv[] )
{
HMODULE hMapiModule = LoadLibrary( _T( "mapi32.dll" ) );
if ( hMapiModule != NULL )
{
LPMAPIINITIALIZE lpfnMAPIInitialize = NULL;
LPMAPIUNINITIALIZE lpfnMAPIUninitialize = NULL;
LPMAPILOGONEX lpfnMAPILogonEx = NULL;
LPMAPISENDDOCUMENTS lpfnMAPISendDocuments = NULL;
LPMAPISESSION lplhSession = NULL;
lpfnMAPIInitialize = (LPMAPIINITIALIZE)GetProcAddress( hMapiModule, "MAPIInitialize" );
lpfnMAPIUninitialize = (LPMAPIUNINITIALIZE)GetProcAddress( hMapiModule, "MAPIUninitialize" );
lpfnMAPILogonEx = (LPMAPILOGONEX)GetProcAddress( hMapiModule, "MAPILogonEx" );
lpfnMAPISendDocuments = (LPMAPISENDDOCUMENTS)GetProcAddress( hMapiModule, "MAPISendDocuments" );
if ( lpfnMAPIInitialize && lpfnMAPIUninitialize && lpfnMAPILogonEx && lpfnMAPISendDocuments )
{
HRESULT hr = (*lpfnMAPIInitialize)( NULL );
if ( SUCCEEDED( hr ) )
{
hr = (*lpfnMAPILogonEx)( 0, NULL, NULL, MAPI_EXTENDED | MAPI_USE_DEFAULT, &lplhSession );
if ( SUCCEEDED( hr ) )
{
// this opens the email client with "C:\attachment.txt" as an attachment
hr = (*lpfnMAPISendDocuments)( 0, ";", "C:\\attachment.txt", NULL, NULL );
if ( SUCCEEDED( hr ) )
{
hr = lplhSession->Logoff( 0, 0, 0 );
hr = lplhSession->Release();
lplhSession = NULL;
}
}
}
(*lpfnMAPIUninitialize)();
}
FreeLibrary( hMapiModule );
}
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With