发送电子邮件的命令行C ++程序

时间:2010-10-06 12:22:16

标签: c++ visual-studio-2008 email

我正在使用VS2008& C ++和我正在尝试创建一个发送电子邮件的命令行程序 我已经上线并找到了一些示例程序,但没有人会为我编译 有没有人有我的示例程序? 感谢

3 个答案:

答案 0 :(得分:2)

此代码编译&为我运行 - 在确定正确的标题后等仍然需要命令行处理,并且不推荐使用MAPI库,但是你想要免费的是什么?来自codeproject.com的原始代码

#include "windows.h"
#include "tchar.h"

#include "mapi.h"
#include "assert.h"
#define ASSERT assert
#define VERIFY assert

BOOL SendMail(CHAR *lpszFrom, CHAR *lpszTo, CHAR *lpszSubject, CHAR *lpszMessage)
{
   BOOL bSent = FALSE;

   HINSTANCE hMAPI = ::LoadLibrary(_T("mapi32.dll"));
   if(0==hMAPI) return bSent;

   typedef ULONG (FAR PASCAL *PFN_MAPILogon)(ULONG,LPTSTR,LPTSTR,FLAGS,ULONG,LPLHANDLE);
   typedef ULONG (FAR PASCAL *PFN_MAPISendMail)(LHANDLE,ULONG,lpMapiMessage,FLAGS,ULONG);
   typedef ULONG (FAR PASCAL *PFN_MAPILogoff)(LHANDLE,ULONG,FLAGS,ULONG);

   PFN_MAPILogon MAPILogon = (PFN_MAPILogon)::GetProcAddress(hMAPI,"MAPILogon");
   PFN_MAPISendMail MAPISendMail = (PFN_MAPISendMail)::GetProcAddress(hMAPI,"MAPISendMail");
   PFN_MAPILogoff MAPILogoff = (PFN_MAPILogoff)::GetProcAddress(hMAPI,"MAPILogoff");

   const BOOL bFunctionsLoaded = (0!=MAPILogon)&&(0!=MAPISendMail)&&(0!=MAPILogoff);
   ASSERT(bFunctionsLoaded);

   if(bFunctionsLoaded)
   {

      LHANDLE session = 0;
      VERIFY(SUCCESS_SUCCESS==MAPILogon(0,0,0,MAPI_NEW_SESSION,0,&session));
      ASSERT(0!=session);

      MapiRecipDesc recipient;
      ::ZeroMemory(&recipient,sizeof(recipient));
      recipient.ulRecipClass = MAPI_TO;
      recipient.lpszName = lpszTo;

      MapiMessage message;
      ::ZeroMemory(&message,sizeof(message));
      message.lpszSubject = lpszSubject;
      message.lpszNoteText = lpszMessage;
      message.nRecipCount = 1;
      message.lpRecips = &recipient;

      bSent = SUCCESS_SUCCESS == MAPISendMail(session,0,&message,0,0);

      VERIFY(SUCCESS_SUCCESS==MAPILogoff(session,0,0,0));

   }

   ::FreeLibrary(hMAPI);

   return bSent;
}

int _tmain(int argc, _TCHAR* argv[])
{
   SendMail("from_you@go_daddy.com","to.someone@gmail.com","Test subject","New Message");
    return 0;
}

答案 1 :(得分:1)

答案 2 :(得分:0)

由于您的服务器是Exchange,因此编写程序以发送电子邮件的最方便方法是使用C#和System.Net.Mail,如演示here。这是C ++ / CLI代码:

   static void CreateTestMessage2( String^ server )
   {
      String^ to = L"jane@contoso.com";
      String^ from = L"ben@contoso.com";
      MailMessage^ message = gcnew MailMessage( from,to );
      message->Subject = L"Using the new SMTP client.";
      message->Body = L"Using this new feature, you can send an e-mail message from an application very easily.";
      SmtpClient^ client = gcnew SmtpClient( server );

      // Credentials are necessary if the server requires the client 
      // to authenticate before it will send e-mail on the client's behalf.
      client->UseDefaultCredentials = true;
      client->Send( message );
      client->~SmtpClient();
   }

如果你真的想使用原生C ++(即不通过C ++ / CLI访问System.Net.Mail),那么你就会遇到一个描述here的原生API。

但是,您可以按照blat所述使用MapiSend或here