Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I programmatically send an email in the same way that I can "Send To Mail Recipient" in Windows Explorer?

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.

like image 758
KRFournier Avatar asked Nov 04 '08 16:11

KRFournier


2 Answers

You can use a standard "mailto:" command in windows shell. It will run the default mail client.

like image 30
TcKs Avatar answered Oct 14 '22 14:10

TcKs


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;
}
like image 130
Jeff Hillman Avatar answered Oct 14 '22 15:10

Jeff Hillman