Click here to Skip to main content
11,584,612 members (67,447 online)
Click here to Skip to main content

Send mail without specifying an SMTP server

, 12 Apr 2005 Ms-PL 1.1M 4.6K 109
Rate this:
Please Sign up or sign in to vote.
A class derived from CSMTPConnection that queries the MX record for a target domain and uses that to send mail

Overview

Quite frequently, you hear people asking how they can send an email from their applications to a specific email address without prompting the user for a relaying SMTP server. The most commonly suggested solution is to use MAPI and get a list of SMTP servers from the user's registry, but this assumes that the user has configured a MAPI compliant email client on his machine. I always reply with my solution of querying the MX record for the target domain and then SMTP-chatting to that server directly - it's easy to do, it works on any machine and it's also the fastest way to send email (minimum number of SMTP hops).

Starting with VC++ 7, ATL includes the CSMTPConnection class which lets you send mail, provided you give it an SMTP server to connect to. I derived a class (CSMTPConnection2) from CSMTPConnection which lets you pass in the target domain name directly and the class queries the MX records using the default DNS on the client machine, gets a list of SMTP servers (depending on the number of MX records returned) and connects to the first SMTP server that works okay. The only visible change is to the Connect method, and even for the Connect method, the method signature remains the same. The first parameter (an LPCTSTR) now represents the target domain name instead of the SMTP hostname. So it should be pretty easy to modify your existing code. Just change all references to CSMTPConnection in your code to CSMTPConnection2 and you are done.

Using the class

  • #include the header file for the class

    #include "smtpconnection2.h"

    The header file includes a #pragma linker directive to include Dnsapi.lib

  • Use the CSMTPConnection2 class just as you would use the CSMTPConnection class (it's assumed that CoInitialize has been called prior to invoking and using this class)

    CMimeMessage msg;
    msg.SetSender("nish@somedomain.com");
    msg.SetSenderName("Nishter");
    msg.AddRecipient("someone@vsnl.com");
    
    //Optional
    msg.SetSubject("Hello World");
    msg.AddText("Hmmm, this should work fine!");
    //msg.AttachFile("some file path");
    
    CSMTPConnection2 conn;
    //You need to specify the domain name of the recipient email address
    if(conn.Connect("vsnl.com"))
    {
        if( conn.SendMessage(msg) == TRUE )
            std::cout << "Mail sent successfully" << std::endl;
        conn.Disconnect();    
    }
    

Class requirements

  • You'll need VC++ 7 or above (for the ATL classes)

  • This code will run only on Windows 2000 or later (because of the DNS API that's used to query the MX record)

  • You do not need MFC (the CString that's used is shared between MFC/ATL and I specifically used CSimpleArray instead of an MFC array class)

Limitation

Note that, because the class looks up the MX record and SMTPs directly into the mail server for each domain name, you cannot use this class to send mails to multiple-domains in one go.

Source listings

Header file

/*
    Copyright(C) Nishant Sivakumar (nish#voidnish.com)
    Please maintain this copyright notice if you distribute this file
    in original or modified form.
*/

#pragma once
#include <atlsmtpconnection.h>
#include <Windns.h>

#pragma comment(lib,"Dnsapi.lib")

class CSMTPConnection2 : public CSMTPConnection
{
public:    
    BOOL Connect(LPCTSTR lpszHostDomain, DWORD dwTimeout = 10000) throw();
private:
    void _GetSMTPList(LPCTSTR lpszHostDomain, CSimpleArray<CString>& arrSMTP);
}; 

Cpp file

/*
    Copyright(C) Nishant Sivakumar (nish#voidnish.com)
    Please maintain this copyright notice if you distribute this file
    in original or modified form.
*/

#include "StdAfx.h"
#include "smtpconnection2.h"

BOOL CSMTPConnection2::Connect(LPCTSTR lpszHostDomain, 
                               DWORD dwTimeout /*= 10000*/) throw()
{
    CSimpleArray<CString> arrSMTP;
    _GetSMTPList(lpszHostDomain, arrSMTP);
    for(int i=0; i<arrSMTP.GetSize(); i++)
    {
        if(CSMTPConnection::Connect(arrSMTP[i], dwTimeout) == TRUE)
            return TRUE;
    }
    return FALSE;
}

void CSMTPConnection2::_GetSMTPList(LPCTSTR lpszHostDomain, 
                                   CSimpleArray<CString>& arrSMTP)
{
    PDNS_RECORD pRec = NULL;
    if(DnsQuery(lpszHostDomain, DNS_TYPE_MX, DNS_QUERY_STANDARD,
        NULL, &pRec, NULL) == ERROR_SUCCESS)
    {
        PDNS_RECORD pRecOrig = pRec;
        while(pRec)
        {
            if(pRec->wType == DNS_TYPE_MX)
                arrSMTP.Add(pRec->Data.MX.pNameExchange);
            pRec = pRec->pNext;
        }
        DnsRecordListFree(pRecOrig,DnsFreeRecordList);
    }
} 

Conclusion

As usual, feedback is welcome and appreciated whether it's constructive or not.

License

This article, along with any associated source code and files, is licensed under The Microsoft Public License (Ms-PL)

Share

About the Author

Nish Nishant
United States United States
Nish Nishant is a Software Architect/Consultant based out of Columbus, Ohio. He has over 15 years of software industry experience in various roles including Lead Software Architect, Principal Software Engineer, and Product Manager. Nish is a recipient of the annual Microsoft Visual C++ MVP Award since 2002 (13 consecutive awards as of 2014).

Nish is an industry acknowledged expert in the Microsoft technology stack. He authored
C++/CLI in Action for Manning Publications in 2005, and had previously co-authored
Extending MFC Applications with the .NET Framework for Addison Wesley in 2003. In addition, he has over 140 published technology articles on CodeProject.com and another 250+ blog articles on his
WordPress blog. Nish is vastly experienced in team management, mentoring teams, and directing all stages of software development.

Contact Nish : You can reach Nish on his google email id voidnish.

Website and Blog

You may also be interested in...

Comments and Discussions

 
GeneralMy vote of 5 Pin
zriniadhi13-Mar-12 2:09
memberzriniadhi13-Mar-12 2:09 
QuestionError 300 - CSMTP_COMMAND_MAIL_FROM Pin
AlexEvans18-Jun-11 12:21
memberAlexEvans18-Jun-11 12:21 
GeneralSend email to multiple recipients who don't belong to the same domain Pin
D.Lakshmankumar7-Jan-10 19:03
memberD.Lakshmankumar7-Jan-10 19:03 
GeneralRe: Send email to multiple recipients who don't belong to the same domain Pin
daluu9-Oct-10 19:11
memberdaluu9-Oct-10 19:11 
GeneralRe: Send email to multiple recipients who don't belong to the same domain Pin
Nishant Sivakumar11-Oct-10 1:55
mvpNishant Sivakumar11-Oct-10 1:55 
Generaldebug assertion failed notifications Pin
eugene pinsky17-Aug-09 8:00
membereugene pinsky17-Aug-09 8:00 
GeneralRe: debug assertion failed notifications [modified] Pin
BEDEK335-Mar-10 11:32
memberBEDEK335-Mar-10 11:32 
I AM GETTING THE SAME BUT -

YOU WROTE -

If I retry and continue, I am able to send e-mail.


ARE YOU REALY SENDING THE MAIL????


FOR ME -


I AM GETTING TRUE RETURN FOR

bb=conn.Connect((LPCTSTR)_bstr_t(aa), 1000);

I AM GETTING FALSE RETURN FOR -

ret=conn.SendMessage(msg);


SO, NO MAIL HAS BEEN SENT...


SO, WHAT ABOUT IMultiLanguage *pMultiLanguage ????


when you used

SetSenderName(LPCTSTR szName, UINT uiCodePage = 0)

you are giving by default uiCodePage = 0

i believe you have to change the value of uiCodePage

thank you.
modified on Friday, March 5, 2010 5:58 PM

GeneralSend without smtp server [modified] Pin
Dipak V Bava28-Feb-09 10:02
memberDipak V Bava28-Feb-09 10:02 
GeneralRe: Send without smtp server Pin
Elmue24-Apr-09 7:11
memberElmue24-Apr-09 7:11 
GeneralRe: Send without smtp server Pin
Dipak V Bava24-Apr-09 7:32
memberDipak V Bava24-Apr-09 7:32 
GeneralRe: Send without smtp server Pin
daluu16-Oct-10 20:32
memberdaluu16-Oct-10 20:32 
QuestionWhat about VC++ 2008? Pin
Member 31360566-Feb-09 22:55
memberMember 31360566-Feb-09 22:55 
AnswerRe: What about VC++ 2008? Pin
Dave Calkins28-Feb-09 3:45
memberDave Calkins28-Feb-09 3:45 
GeneralRe: What about VC++ 2008? Pin
Janma16-May-10 21:12
memberJanma16-May-10 21:12 
GeneralRe: What about VC++ 2008? Pin
daluu9-Oct-10 19:16
memberdaluu9-Oct-10 19:16 
GeneralUseful article Pin
om7-Jan-09 12:33
memberom7-Jan-09 12:33 
QuestionCOM and ActiveX implementation? Pin
daluu1-Nov-08 19:40
memberdaluu1-Nov-08 19:40 
General.NET alternative [modified] Pin
daluu3-Oct-08 20:25
memberdaluu3-Oct-08 20:25 
GeneralQuite useless code! Pin
Elmue17-Jul-08 11:48
memberElmue17-Jul-08 11:48 
Generalatlsmtpconnection.h Pin
theCPkid28-Jun-08 4:06
membertheCPkid28-Jun-08 4:06 
GeneralProps to Nish Pin
bvaghani26-Jan-08 16:31
memberbvaghani26-Jan-08 16:31 
Generalrename Connect to ConnectDomain Pin
Herbert Yu29-Nov-07 10:29
memberHerbert Yu29-Nov-07 10:29 
GeneralRe: rename Connect to ConnectDomain Pin
Yogesh P. Dhakad13-Jan-08 3:03
memberYogesh P. Dhakad13-Jan-08 3:03 
GeneralNot working with all providers [modified] Pin
Manthis18-Nov-07 23:46
memberManthis18-Nov-07 23:46 
GeneralWorks for me on hotmail.com Pin
Herbert Yu29-Nov-07 9:45
memberHerbert Yu29-Nov-07 9:45 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.150707.1 | Last Updated 12 Apr 2005
Article Copyright 2005 by Nish Nishant
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid