e-mail with c/c++

This is a discussion on e-mail with c/c++ within the C++ Programming forums, part of the General Programming Boards category; Hi. All I need real quick is a short example on how to e-mail a message to somebody. For example, ...

  1. #1
    Registered User deltabird's Avatar
    Join Date
    Jan 2003
    Posts
    73

    e-mail with c/c++

    Hi. All I need real quick is a short example on how to e-mail a message to somebody. For example, you have a variable char string[50]. How do you e-mail that to some address?

  2. #2
    I lurk
    Join Date
    Aug 2002
    Posts
    1,361
    Look into Winsock if you're on windows (Edited)
    After that, read up on SMTP (Simple Mail Transfer Protocol)
    Last edited by Eibro; 06-30-2003 at 05:24 PM.

  3. #3
    Registered User deltabird's Avatar
    Join Date
    Jan 2003
    Posts
    73
    is it supported on everyones computer so friends can use it?

  4. #4
    I lurk
    Join Date
    Aug 2002
    Posts
    1,361
    Winsock is supported on *all modern versions of Windows, yes.

  5. #5
    Registered User deltabird's Avatar
    Join Date
    Jan 2003
    Posts
    73
    heres my code but i get errors:
    Code:
    #include <stdio.h>
    #include <io.h>
    
    #include <stdio.h>
    
    //#define LINUX /* define this if you are on linux   */
    //#define WIN32 /* define this if you are on windows */
    
    #ifdef WIN32
    #       include "io.h"
    #       include "winsock2.h"      /* WSAGetLastError, WSAStartUp  */
    #       define snprintf _snprintf
    #endif
    
    #ifdef LINUX
    #       include <netdb.h>         /* gethostbyname  */
    #       include <netinet/in.h>    /* htons          */
    #       include <sys/socket.h>
    #endif
    
    static void sendmail_write(const int  sock,const char *str,const char *arg) 
    {
        char buf[4096];
    
        if (arg != NULL)
            snprintf(buf, sizeof(buf), str, arg);        
        else
            snprintf(buf, sizeof(buf), str);
        
        send(sock, buf, strlen(buf), 0);    
    }
    
    static int sendmail(const char *from,const char *to,const char *subject,const char *body, const char *hostname,const int   port)
    {
        struct hostent *host;   
        struct sockaddr_in saddr_in;
        int sock = 0;
    
    #ifdef WIN32
    	WSADATA wsaData;
    	if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) 
    	{
    		return -1;
    	}
    #endif
    
        sock = socket(AF_INET, SOCK_STREAM, 0);
    	host = gethostbyname(hostname);
    	
    	saddr_in.sin_family      = AF_INET;
    	saddr_in.sin_port        = htons((u_short)port);
    	saddr_in.sin_addr.s_addr = 0;
    
    	memcpy((char*)&(saddr_in.sin_addr), host->h_addr, host->h_length);
    
    	if (connect(sock, (struct sockaddr*)&saddr_in, sizeof(saddr_in)) == -1)
    	{
    		return -2;
    	}
        
        sendmail_write(sock, "HELO %s\n",       from);    // greeting
        sendmail_write(sock, "MAIL FROM: %s\n", from);    // from
        sendmail_write(sock, "RCPT TO: %s\n",   to);      // to
        sendmail_write(sock, "DATA\n",          NULL);    // begin data
    
        // next comes mail headers
        sendmail_write(sock, "From: %s\n",      from);
        sendmail_write(sock, "To: %s\n",        to);
        sendmail_write(sock, "Subject: %s\n",   subject);
    
        sendmail_write(sock, "\n",              NULL);
    
        sendmail_write(sock, "%s\n",            body);    // data
    
        sendmail_write(sock, ".\n",             NULL);    // end data
        sendmail_write(sock, "QUIT\n",          NULL);    // terminate
    
        close(sock);
    
        return 0;
    }
    
    
    int main(int argc, char *argv[]) {
        
        int ret = sendmail(
            "person@hotmail.com",   /* from     */
            "person@hotmail.com",       /* to       */
            "Subject",              /* subject  */
            "body",                 /* body     */
            "mx1.hotmail.com",             /* hostname */
            25                      /* port     */
        );
    
        if (ret != 0)
            fprintf(stderr, "Failed to send mail (code: %i).\n", ret);
        else
            fprintf(stdout, "Mail successfully sent.\n");
    
        return ret;
    }
    
    --------------------Configuration: email - Win32 Debug--------------------
    Linking...
    main.obj : error LNK2001: unresolved external symbol __imp__connect@12
    main.obj : error LNK2001: unresolved external symbol __imp__htons@4
    main.obj : error LNK2001: unresolved external symbol __imp__gethostbyname@4
    main.obj : error LNK2001: unresolved external symbol __imp__socket@12
    main.obj : error LNK2001: unresolved external symbol __imp__WSAStartup@8
    main.obj : error LNK2001: unresolved external symbol __imp__send@16
    LIBCD.lib(wincrt0.obj) : error LNK2001: unresolved external symbol _WinMain@16
    Debug/email.exe : fatal error LNK1120: 7 unresolved externals
    Error executing link.exe.
    
    email.exe - 8 error(s), 0 warning(s)
    whats wrong?

  6. #6
    Registered User
    Join Date
    Jun 2003
    Posts
    2
    did you link to wsock32.lib??

    if you are using microsoft visual c ++ do the following

    under the "project" menu choose settings or press Alt+F7

    choose the link tab

    under "object/library modules" add wsock32.lib

  7. #7
    C++ Developer XSquared's Avatar
    Join Date
    Jun 2002
    Location
    Ontario, Canada
    Posts
    2,718
    >>//#define LINUX /* define this if you are on linux */
    >>//#define WIN32 /* define this if you are on windows */

    You might want to uncomment the one which corresponds to your OS.
    Naturally I didn't feel inspired enough to read all the links for you, since I already slaved away for long hours under a blistering sun pressing the search button after typing four whole words! - Quzah

    You. Fetch me my copy of the Wall Street Journal. You two, fight to the death - Stewie

  8. #8
    Registered User deltabird's Avatar
    Join Date
    Jan 2003
    Posts
    73
    i did it for console (even tried again), but still get thta winmain error. winmain is nowhere in my code. other than that it works now. hmm...

  9. #9
    C++ Developer XSquared's Avatar
    Join Date
    Jun 2002
    Location
    Ontario, Canada
    Posts
    2,718
    You're sure that its a Win32 Console App, not a Win32 App?
    Naturally I didn't feel inspired enough to read all the links for you, since I already slaved away for long hours under a blistering sun pressing the search button after typing four whole words! - Quzah

    You. Fetch me my copy of the Wall Street Journal. You two, fight to the death - Stewie

  10. #10
    Registered User deltabird's Avatar
    Join Date
    Jan 2003
    Posts
    73
    k i got it to run but i don't get the email...

  11. #11
    Registered User deltabird's Avatar
    Join Date
    Jan 2003
    Posts
    73

    new smtp code doesn't work

    Ok, here's an example I found on google, with 1 error:
    Code:
    #include <comdef.h>
    #include <iostream>
    #include "ansmtp.tlh"
    using namespace ANSMTPLib;
    using namespace std;
    
    void SendEmail()
    {
      ::CoInitialize( NULL );
      IOBJPtr oSmtp = NULL;
      oSmtp.CreateInstance("ANSMTP.OBJ");
    	
      oSmtp->ServerAddr = _bstr_t( "mail.adminsystem.net" );
      oSmtp->FromAddr = _bstr_t( "test@adminsystem.net" );
      oSmtp->AddRecipient( _bstr_t("Support Team"), 
                          _bstr_t("support@adminsystem.net"), 0 );
    
      oSmtp->Subject = _bstr_t("Test");
      oSmtp->BodyText = _bstr_t("Hello, this is a test....");
      
      if( oSmtp->SendMail() == 0 )
        cout << "Message delivered!" << endl;
      else
        cout << (const char*)(oSmtp->GetLastErrDescription()) << endl;
    }
    
    int main(int argc, char* argv[])
    {
      SendEmail();
      return 0;
    }
    
    testmailertest\main.cpp(32) : fatal error C1010: unexpected end of file while looking for precompiled header directive

  12. #12
    Registered User deltabird's Avatar
    Join Date
    Jan 2003
    Posts
    73
    oh, and the other one doesn't actually send the mail....

  13. #13
    Just one more wrong move. -KEN-'s Avatar
    Join Date
    Aug 2001
    Posts
    3,230
    Do you have the file "ansmtp.tlh"?

  14. #14
    I lurk
    Join Date
    Aug 2002
    Posts
    1,361

    Re: new smtp code doesn't work

    Originally posted by deltabird
    Ok, here's an example I found on google, with 1 error:
    Code:
    #include <comdef.h>
    #include <iostream>
    #include "ansmtp.tlh"
    using namespace ANSMTPLib;
    using namespace std;
    
    void SendEmail()
    {
      ::CoInitialize( NULL );
      IOBJPtr oSmtp = NULL;
      oSmtp.CreateInstance("ANSMTP.OBJ");
    	
      oSmtp->ServerAddr = _bstr_t( "mail.adminsystem.net" );
      oSmtp->FromAddr = _bstr_t( "test@adminsystem.net" );
      oSmtp->AddRecipient( _bstr_t("Support Team"), 
                          _bstr_t("support@adminsystem.net"), 0 );
    
      oSmtp->Subject = _bstr_t("Test");
      oSmtp->BodyText = _bstr_t("Hello, this is a test....");
      
      if( oSmtp->SendMail() == 0 )
        cout << "Message delivered!" << endl;
      else
        cout << (const char*)(oSmtp->GetLastErrDescription()) << endl;
    }
    
    int main(int argc, char* argv[])
    {
      SendEmail();
      return 0;
    }
    
    testmailertest\main.cpp(32) : fatal error C1010: unexpected end of file while looking for precompiled header directive
    Easy solution to this problem, and your other unresolved external WinMain.

    To fix the precompiled header error go:
    Project->Settings->C/C++->Category: Precompiled Headers and select "Not using precompiled headers"

    To fix the linker error:
    Project->Settings->Link
    In the Project Options textbox, scroll down until you see /subsystem:#######, where ####### is either "console" or "windows". Remove this line.

    These should really be in the FAQ...

  15. #15
    Registered User deltabird's Avatar
    Join Date
    Jan 2003
    Posts
    73
    Alright, well it's still not sending for some reason. It stops when it says "354 Please start mail input" and there ARE lines after that that it sould write. Here's the code:
    Code:
    #include <stdio.h>
    #include <io.h>\
    
    int  rc;
        char buf[256];
    
    //#define LINUX /* define this if you are on linux   */
    //#define WIN32 /* define this if you are on windows */
    
    #ifdef WIN32
    #       include "io.h"
    #       include "winsock2.h"      /* WSAGetLastError, WSAStartUp  */
    #       define snprintf _snprintf
    #endif
    
    #ifdef LINUX
    #       include <netdb.h>         /* gethostbyname  */
    #       include <netinet/in.h>    /* htons          */
    #       include <sys/socket.h>
    #endif
    
    #pragma comment(lib, "wsock32.lib")
    
    static void sendmail_write(const int  sock,const char *str,const char *arg) 
    {
        char buf[4096];
    
        if (arg != NULL)
            snprintf(buf, sizeof(buf), str, arg);        
        else
            snprintf(buf, sizeof(buf), str);
        
        send(sock, buf, strlen(buf), 0); 
    	
    	if ((rc = recv(sock, buf, sizeof(buf) - 1, 0)) == -1) {
        perror("recv");
    	} else {
        buf[rc] = 0;
        printf("%s", buf);
    	}
    }
    
    static int sendmail(const char *from,const char *to,const char *subject,const char *body, const char *hostname,const int   port)
    {
        struct hostent *host;   
        struct sockaddr_in saddr_in;
        int sock = 0;
    
    #ifdef WIN32
    	WSADATA wsaData;
    	if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) 
    	{
    		return -1;
    	}
    #endif
    
        sock = socket(AF_INET, SOCK_STREAM, 0);
    	host = gethostbyname(hostname);
    	
    	saddr_in.sin_family      = AF_INET;
    	saddr_in.sin_port        = htons((u_short)port);
    	saddr_in.sin_addr.s_addr = 0;
    
    	memcpy((char*)&(saddr_in.sin_addr), host->h_addr, host->h_length);
    
    	if (connect(sock, (struct sockaddr*)&saddr_in, sizeof(saddr_in)) == -1)
    	{
    		return -2;
    	}
        
        sendmail_write(sock, "helo %s\r\n",       from);    // greeting
        sendmail_write(sock, "mail from: %s\r\n", from);    // from
        sendmail_write(sock, "rcpt to: %s\r\n",   to);      // to
        sendmail_write(sock, "data\r\n\n",        NULL);    // begin data
    
        // next comes mail headers
        sendmail_write(sock, "From: %s\r\n",      from);
        sendmail_write(sock, "To: %s\r\n",        to);
        sendmail_write(sock, "Subject: %s\r\n",   subject);
    	sendmail_write(sock, "Date: 6/6/6\r\n", NULL);
    
        sendmail_write(sock, "\r\n",              NULL);
    
        sendmail_write(sock, "%s\r\n",            body);    // data
    
        sendmail_write(sock, ".\r\n",             NULL);    // end data
    	//Sleep(5000);
        sendmail_write(sock, "QUIT\r\n",          NULL);    // terminate
    
        #ifdef WIN32
        closesocket(sock);
        #else
        close(sock);
        #endif
    
        return 0;
    }
    
    int main(int argc, char *argv[]) {
    
    	
        
        int ret = sendmail(
            "sparknote_s@hotmail.com",   /* from     */
            "sparknote_s@hotmail.com",       /* to       */
            "Subject",              /* subject  */
            "body",                 /* body     */
            "mx2.hotmail.com",             /* hostname */
            25                      /* port     */
        );
    
        if (ret != 0)
            fprintf(stderr, "Failed to send mail (code: %i).\n", ret);
        else
            fprintf(stdout, "Mail successfully sent.\n");
    
        return ret;
    }

Page 1 of 3 123 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Trouble with DMA Segmentation Faults
    By firestorm717 in forum C Programming
    Replies: 2
    Last Post: 05-07-2006, 10:20 PM
  2. mail application
    By terracota in forum Networking/Device Communication
    Replies: 6
    Last Post: 07-31-2004, 05:36 PM
  3. Yahoo! Mail launch NEW features
    By beely in forum A Brief History of Cprogramming.com
    Replies: 19
    Last Post: 06-21-2004, 11:05 PM
  4. Mail Accounts?
    By ZakkWylde969 in forum A Brief History of Cprogramming.com
    Replies: 6
    Last Post: 06-20-2004, 01:57 PM
  5. the MAIL command in UNIX and Pipes
    By RoshanX in forum Linux Programming
    Replies: 19
    Last Post: 10-21-2003, 11:40 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21