当前位置:编程学习 > 网站相关 >>

如何在MFC应用程序中使用MAPI32.DLL发送电子邮件

[问题]

如何在MFC应用程序中使用MAPI32.DLL发送电子邮件。

[解答]

/*加上头文件*/
#include <mapi.h>
#include <stdlib.h>

/* 定义SendEmail函数的返回值*/
#define SENDEMAIL_SUCCESS               0 //邮件成功发送
#define SENDEMAIL_MAPI_NOT_INSTALLED    1 //没有安装MAPI Server
#define SENDEMAIL_MAPILOAD_FAILED       2 //加载 MAPI32.DLL 失败
#define SENDEMAIL_LOGON_FAILED          3 //无法登陆到 MAPI Server 或者 用户取消了登陆框
#define SENDEMAIL_SEND_FAILED           4 //消息发送失败

int SendEmail(const char* Address,
     const char* Subject, 
     const char* Text)
{
    int             iResult;
    UINT            iMapiInstalled;
    HINSTANCE       hMAPIInst;
    LPMAPILOGON     pMAPILogon;
    LPMAPILOGOFF    pMAPILogoff;
    LPMAPISENDMAIL  pMAPISendMail;
    LHANDLE         lhSession;

    iResult         = SENDEMAIL_SUCCESS;

    iMapiInstalled  = GetProfileInt("Mail", "MAPI", 0);

    if(! iMapiInstalled)
        return SENDEMAIL_MAPI_NOT_INSTALLED;

    hMAPIInst       = LoadLibrary("MAPI32.DLL");
    if(!hMAPIInst)
        return SENDEMAIL_MAPILOAD_FAILED;

    pMAPILogon      = (LPMAPILOGON)
                      GetProcAddress(hMAPIInst, "MAPILogon");
    pMAPILogoff     = (LPMAPILOGOFF)
                      GetProcAddress(hMAPIInst, "MAPILogoff");
    pMAPISendMail   = (LPMAPISENDMAIL)
                      GetProcAddress(hMAPIInst, "MAPISendMail");

    if(pMAPILogon(0, NULL, NULL, MAPI_LOGON_UI, 0, &lhSession)
        != SUCCESS_SUCCESS)
    {
        iResult = SENDEMAIL_LOGON_FAILED;
    }
    else        /* Send the Message         */
    {
        ULONG       Result;
        MapiMessage Msg;

        MapiRecipDesc Recipients[1];
        Recipients[0].ulReserved = 0;
        Recipients[0].ulRecipClass = MAPI_TO;
        Recipients[0].lpszName = (char*)Address;
        Recipients[0].lpszAddress = (char*)Address;
        Recipients[0].ulEIDSize = 0;
        Recipients[0].lpEntryID = 0;

        memset(&Msg, 0, sizeof(Msg));
        Msg.lpszSubject         = (char*)Subject;
        Msg.lpszNoteText        = (char*)Text;
        Msg.nRecipCount         = 1;
        Msg.lpRecips            = Recipients;

        Result      = pMAPISendMail(lhSession, 0, &Msg, 0, 0);
        if(Result != SUCCESS_SUCCESS)
            iResult = SENDEMAIL_SEND_FAILED;

        pMAPILogoff(lhSession, 0, 0, 0);
    }

    FreeLibrary(hMAPIInst);

    return iResult;
}

调用方法:
rc = SendEmail("SMTP:hangwire@sina.com", "一个小测试","你好, 其实这很简单。");

补充:综合编程 , 安全编程 ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,