Using MAPI to Send E-Mail

Environment: ATL, COM, Visual C++ 6, MFC, Microsoft Outlook Express, Win XP, Win 2000

Introduction

During software development, I have seen many applications that require incorporating e-mail support. I remember once I was to develop an application that sends e-mails at a specific time to specific people with the customized messages. For that, I developed a COM service that used MAPI. MAPI, or Messaging Application Programming Interface, is the standard messaging architecture and a complete set of functions and object-oriented interfaces. Here I have an Email component and a COM DLL, which is a set of messaging functions that helps you create messaging-enabled applications.

Note: MAPI is used by various industry-standard e-mail clients, such as the Microsoft Exchange client, all versions of Microsoft Outlook and Outlook Express, including QUALCOMM Incorporated (Eudora) and Netscape Communications Corporation. So, you can use this component with these client applications also.

Component Design

The CLSID of the E-mail component is CLSID_Mail and it has only one interface, IMail, with the interface ID IID_IMail.

CMail is the implementation class and contains the following data members:

Data MemberFunction Pointer for
m_MAPILogonMAPILogon
m_MAPISendMailMAPISendMail
m_MAPISendDocuments  MAPISendDocuments
m_MAPIFindNextMAPIFindNext
m_MAPIReadMailMAPIReadMail
m_MAPIResolveNameMAPIResolveName
m_MAPIAddressMAPIAddress
m_MAPILogoffMAPILogoff
m_MAPIFreeBufferMAPIFreeBuffer
m_MAPIDetailsMAPIDetails
m_MAPISaveMailMAPISaveMail

IMail has the following functions:

FunctionDescription
IsMapiInstalled Checks whether the MAPI is installed on the system. It searches the Win.INI file for the MAPI key. If found, it returns S_OK.
InitMapiAfter checking through IsMapiInstalled, it initializes the MAPI function pointers. The method should be called once before using the component.
put_strProfileNameTakes the name of the Outlook profile name you are using to send the e-mail.
put_strEmailAddressSets the recipient e-mail address. You can specify more than one comma (,) separated recipient addresses.
put_strRecipientThe name you want to specify for the recipients, sets the e-mail names of the sender—it may be different from your specified profile e-mail address.
put_strSubjectSets the subject of the e-mail
get_strSubjectReturns the e-mail subject
put_strMessageSets e-mail message text
get_strMessageReturns message text
put_strAttachmentFilePath  Sets the e-mail attachment with the full path, such as "c:\abc.txt"
get_strAttachmentFilePathReturns the path of the e-mail attachment
put_strAttachmentFileThe display name of the attachment (Sample.txt); by default, its the same as that of specified in put_strAttachmentFilePath.
get_strAttachmentFileReturns the attachment file name
LogonOpens a new logon session if not already opened, using specified outlook profile, name and the profile password; you must logon before sending the e-mail. I have set the password to NULL, assuming that the profile you will specify have NO password, but you can specify your own password. Automatically called by Send method.
LogoffLog off, and closes the session. Automatically called by the Send method after sending the e-mail.
Send Sends the e-mail, requires valid Outlook profile name, recipient e-mail address, and a login session to send e-mail.

Steps to Execute the Demo Project

The demo project demonstrates the way you can use the component to send an e-mail. To execute the demo project, the following settings are required:

Step 1: You must have some valid Output Express e-mail account or create one named TestProfile.

You can create an e-mail profile in Express from the Tools>Accounts menu. This will open the Internet Accounts property sheet. On the All tab, click Add and then Mail. A wizard will let you create an e-mail account and specify the valid e-mail address. For a Hotmail account, the wizard automatically sets the names of e-mail servers.



Click here for a larger image.

After successfully creating the account, select the account name from the list on the All tab (for a Hotmail account, the default account name is Hotmail). Open the account's properties by pressing the Properties button and change the account name from the default name (say Hotmail) to TestProfile.

Step 2: Register the DLL

All COM DLLs are required to be registered. After copying the DLL source code, you can register the DLL by right-clicking the DLL and selecting the Register DLL or Register COM component option, or simply by double-clicking the DLL. Compiling the DLL code in Visual Studio will automatically register the DLL.

Step 3: Log on to the net

Make sure you are logged on to the net. If not, Outlook will fail to deliver the e-mail; however, you can still check the composed e-mail in your outbox.

How to Send E-Mail

After specifying the information in the dialog box, click the Send button. A warning message will be displayed; click the Send button.

Note: These dialog boxes are displayed just to demonstrate the process. You can even hide them.

Here is the CTestEmailDlg::OnSend method, which is used to pass the user-specified information to the e-mail object and calls the IMail::Send method after setting everything.

//##//##//////////////////////////////////////////////////////////

///////////////////////////////////////////////
//
//  void CTestEmailDlg::OnSend()
//
//    This module is called when the Send button is pressed and
//    uses the Email COM DLL to send e-mail - Aisha Ikram
// Note: Don't forget to initialize the COM library using
// CoInitialize(NULL);
//##//##//////////////////////////////////////////////////////////

///////////////////////////////////////////////

void CTestEmailDlg::OnSend()
{
  UpdateData();
  try{

  CComPtr objMail;

  HRESULT hr;
  // make sure the DLL is registered
  hr = objMail.CoCreateInstance(CLSID_Mail);
  if(SUCCEEDED(hr))
  {
  if(hr== S_OK)
  {
  // Profile name is compulsory; this is the Outlook profile.
  // I used "Outlook Express" because configuring it is easier
  // than "MS Outlook."
  // Make sure to specify the correct sender's address for this
  // profile and make sure that Outlook Express is the default
  // e-mail client.

     if(m_strProfile.IsEmpty())
     {
    AfxMessageBox("Please specify email profile name ");
    return;
      }

     if(m_strTo.IsEmpty())
     {
    AfxMessageBox("Please specify recipient's email address ");
    return;
      }
      // by default, it's TestProfile, assumes that a profile
      // with this name exists in outlook
      hr= objMail->put_strProfileName((_bstr_t)m_strProfile);

      hr = objMail->put_strSubject((_bstr_t)m_strSubject);

      // this is the e-mail or set of e-mail addresses
      // (separated by ,) which is actually used to send email
      hr = objMail->put_strEmailAddress((_bstr_t)m_strTo);

      // recipient is just to show the display name
      hr = objMail->put_strRecipient((_bstr_t)m_strTo);

      hr = objMail->put_strAttachmentFilePath((_bstr_t)
           m_strAttachment);

      hr = objMail->put_strMessage((_bstr_t)m_strMessage);

      hr= objMail->Send();

      if(hr!=S_OK)
    AfxMessageBox("Error, make sure the info is correct");
    }   //if
  }     //if
    }   //try
   catch(...)
   {
  AfxMessageBox("Error, make sure specified info is correct");
   }
}

Check the mail in the recepient inbox.

Where to Use the Component

This component can be extended to incorporate functionalities such as opening an existing inbox to read e-mails automatically from the Inbox, composing new e-mails, and so forth. It can be used to automatically send e-mails with customized user messages and attachments to specific people at a particular time, especially when using some .exe servers or NT services.

About the Author

Aisha is an M.Sc.in Computer Science with a top position in her university. She has worked mainly in VC++ 6, MFC, ATL, COM/DCOM, ActiveX, C++, ASP, VB, SQL, and so on. These days, she is working on the dot-Net framework, managed C++, and C#. She is inspired by nature and loves to seek knowledge. She is so fond of travelling that she don't want to die without seeing this whole world.

Website: http://aisha.hostmb.com
E-mail: aisikr@yahoo.com

If there are any suggestions or comments, you are most welcome to contact me. My Web site is http://aisha.hostmb.com.

Downloads

Download Demo project - 116 Kb
Download Source project - 229 Kb


Comments

  • You thirst for some tomato basil and mozzarella. In behalf of indoor say, these slippers are as sparkle and manueverable as sneakers.

    Posted by Soaceddew on 04/19/2013 02:48pm

    Has honourable released distinct new color Subject to Inneva Woven shoes, Nike recently with another pathway to discuss shoes with different styling to all [url=http://markwarren.org.uk/goodbuy.cfm]nike free run[/url] eyes. This brings important issue Unfastened Inneva Woven is a Chaste Marker of works in the series, represents shoes Italian made the assurance. Latest Free Inneva Woven clouded and bawdy are on tap in two color schemes, to hand-knit Woven vamp in addition to infiltrated Italy's [url=http://markwarren.org.uk/goodbuy.cfm]nike free run uk[/url] finest crafts, for the moment gives athletes close to the foot of relieve, the most consequential thing is the end of Unused 5 configuration, barefoot know it pass on give birth to cannot be ignored. Nike Sovereign Inneva Woven SP Pale-complexioned Characterization Order off on March 16 at outlets for everyone the [url=http://fossilsdirect.co.uk/glossarey.cfm]nike huarache[/url] kind on the shelves, and on in stock in minimal form, interested friends should settle clinch attention to Nike announced the news.

    Reply
  • ask

    Posted by Dina09 on 03/28/2011 10:00pm

    Hi.... I tried your project and do all procedure but still can't run I use microsoft outlook, windows 7, and visual studio 2010 are something wrong with that? thank you

    Reply
  • Please send me ur mail that i can ask more questions.

    Posted by nazrulit2003 on 02/17/2007 10:52am

    You are there for ur hard word. Pray for me that i can come up ur stage very soon.

    Reply
  • Hi

    Posted by nazrulit2003 on 02/17/2007 10:50am

    Thank You for ur guidance. I will never forget u.

    Reply
  • Outlook Express default mial client..

    Posted by Legacy on 12/18/2003 12:00am

    Originally posted by: vaidhya

    Hi!
    Is there any way to find the defualt mail client of an outlook by our app..

    Reply
  • ActiveX Control

    Posted by Legacy on 12/28/2002 12:00am

    Originally posted by: C M Praveen Narayan

    I want to create an ActiveX Control which can able to play a video clip.It should contain buttons to Play,Pause,Mute and Stop.
    Can anybody help me to implement this..While clicking the buttons it has to do the particular functionality,like play,pause etc.I implemented the functionality,i want to know how i can implement with activex control.

    Hoping a reply soon,

    warm regards,
    Praveen.

    Reply
  • Good, but...

    Posted by Legacy on 12/24/2002 12:00am

    Originally posted by: ZHEFU ZHANG

    Thanks for your good article. Just a small question: There are several articles on MAPI sending mail to ..., but all need we set up a account in Outlook express ahead, and besides, say from IE, the user can set an option in Outlook "Remind me if any mail sent out under my name"(or sth like this). And I am sure it will intercept your trying to send the mail.
    The last point is: Is there any way to send a mail even there is none account in the outlook express. AND is there a way to play with hotmail(HTTP mail) directly?
    Thank you again and Merry Christmas 2002!

    Best Regards,

    jeff

    • Hmm

      Posted by alophone on 03/24/2005 06:48am

      OK

      Reply
    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • On-demand Event Event Date: September 10, 2014 Modern mobile applications connect systems-of-engagement (mobile apps) with systems-of-record (traditional IT) to deliver new and innovative business value. But the lifecycle for development of mobile apps is also new and different. Emerging trends in mobile development call for faster delivery of incremental features, coupled with feedback from the users of the app "in the wild." This loop of continuous delivery and continuous feedback is how the best mobile …

  • Webinar on September 23, 2014, 2 p.m. ET / 11 a.m. PT Mobile commerce presents an array of opportunities for any business -- from connecting with your customers through mobile apps to enriching operations with mobile enterprise solutions. Join guest speaker, Michael Facemire, Forrester Research, Inc. Principal Analyst, as he discusses the new demands of mobile engagement and how application program interfaces (APIs) play a crucial role. Check out this upcoming webinar to learn about the new set of …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds