Examples › Socket Examples
socket_imap_client
Legacy: examples_socket/imap_client/testprog.cpp · Modern: examples_modern/socket/imap_client/modern.cpp
Modern equivalent of the IMAP client example (6.4). gxsIMAPClient already has a std::string interface (Connect, Login, Capability into a std::vector<std::string>); this example uses it with C++20: the capability list is searched with std::ranges::find, mailbox counts come back through a structured result, and the commands to run are a std::vector walked with a range-for. With no arguments a scripted server on 127.0.0.1 answers (plain text, allowed only because it is a local test: AllowPlainLogin()); with "HOST USER PASSWORD" the client connects with TLS to port 993.
Legacy calls in this program
| Legacy | Modern C++ | Standard | Notes |
|---|---|---|---|
| Atoi(), Atol(), Atof(), atoi() | std::from_chars() into std::optional<T>; std::stoi() | C++17 | Overflow and junk are reported, not turned into 0. |
| SetWidth(), SetFill(), Precision(), sprintf() | std::format("{:*>10} {:.3f}", ...) | C++20 | C++17 and older: <iomanip> setw, setfill, setprecision. |
| strcpy(), strncpy(), memmove() into char arrays | std::string; std::array<char, N> + string_view::copy() | C++11 / C++17 | |
| gxsHTTPClient, gxsSMTPClient, gxsPOP3Client, gxsIMAPClient, gxsFTPClient, gxsTelnetClient | keep them; std::string buffers; reply parsing with std::string_view and std::from_chars | C++17 |
From the transition tables.
Side by side
DataReel 6.4 (legacy)
examples_socket/imap_client/testprog.cpp 179 lines
#include "gxdlcode.h" #include <stdio.h> #include <string.h> #include <stdlib.h> #include <string> #include <vector> #include "gxsimap.h" #if defined (__WIN32__) #include <io.h> #include <fcntl.h> #endif #ifdef __MSVC_DEBUG__ #include "leaktest.h" #endif static void Usage(const char *prog) { printf("Usage: %s [--port N] [--starttls | --plain [--allow-plain]]\n" " [--ca FILE] [--name NAME] [--no-verify] [--log] server username command " "[arguments]\n", prog); printf("Commands: list, count MAILBOX, search MAILBOX WHAT, " "header|body|message|dates|seen|delete MAILBOX N\n"); printf("The password is read from IMAP_PASSWORD or standard input.\n"); } static int Fail(gxsIMAPClient &imap, int show_log) { printf("%s\n", imap.Error().c_str()); if(show_log) printf("%s", imap.ProtoString().c_str()); imap.CloseClient(); return 1; } int main(int argc, char **argv) { #ifdef __MSVC_DEBUG__ InitLeakTest(); #endif #if defined (__WIN32__) // Messages are printed as received, with their CR LF line ends _setmode(_fileno(stdout), _O_BINARY); #endif int port = 0, starttls = 0, plain = 0, allow_plain = 0, verify = 1; int show_log = 0; const char *ca = 0, *name = 0; int i = 1; for(; i < argc && strncmp(argv[i], "--", 2) == 0; i++) { if(strcmp(argv[i], "--port") == 0 && i + 1 < argc) port = atoi(argv[++i]); else if(strcmp(argv[i], "--starttls") == 0) starttls = 1; else if(strcmp(argv[i], "--plain") == 0) plain = 1; else if(strcmp(argv[i], "--allow-plain") == 0) allow_plain = 1; else if(strcmp(argv[i], "--ca") == 0 && i + 1 < argc) ca = argv[++i]; else if(strcmp(argv[i], "--name") == 0 && i + 1 < argc) name = argv[++i]; else if(strcmp(argv[i], "--no-verify") == 0) verify = 0; else if(strcmp(argv[i], "--log") == 0) show_log = 1; else { Usage(argv[0]); return 1; } } if(argc - i < 3) { Usage(argv[0]); return 1; } const char *server = argv[i]; const char *username = argv[i+1]; const char *command = argv[i+2]; const char *mailbox = (argc - i > 3) ? argv[i+3] : "INBOX"; const char *arg = (argc - i > 4) ? argv[i+4] : ""; int use_tls = !(starttls || plain); if(port == 0) port = use_tls ? gxSOCKET_SIMAP_PORT : gxSOCKET_IMAP_PORT; // The password, from the environment or the first input line char password[1024]; password[0] = 0; const char *env = getenv("IMAP_PASSWORD"); if(env) { strncpy(password, env, sizeof(password) - 1); password[sizeof(password) - 1] = 0; } else if(fgets(password, sizeof(password), stdin)) { password[strcspn(password, "\r\n")] = 0; } // 11/16/2026: The calls below are the DataReel 7.4 gxsIMAPClient // interface, which 6.4 also has, so this code builds with either. gxsIMAPClient imap; imap.SetTimeout(60); imap.SetRecordProto(show_log != 0); if(ca) imap.SetCAFile(ca); imap.SetVerifyPeer(verify != 0); #if defined (__USE_GX_SSL_EXTENSIONS__) if(!plain && name) imap.openssl.SetHostName(name); // 6.4 only #endif int crv; if(plain) { if(!allow_plain) { printf("Refusing to send a password without TLS (add --allow-plain)\n"); return 1; } crv = imap.ConnectPlain(server, port); } else { crv = imap.Connect(server, port, starttls ? gxsMAIL_STARTTLS : gxsMAIL_IMPLICIT_TLS); } if(crv != 0) return Fail(imap, show_log); if(imap.Login(std::string(username), std::string(password)) != 0) { memset(password, 0, sizeof(password)); return Fail(imap, show_log); } memset(password, 0, sizeof(password)); int rv = 0; std::string out, out2; if(strcmp(command, "list") == 0) { std::vector<std::string> names; rv = imap.ListMailboxes(names); for(size_t k = 0; rv == 0 && k < names.size(); k++) printf("%s\n", names[k].c_str()); } else { int count = 0; int writes = (strcmp(command, "seen") == 0 || strcmp(command, "delete") == 0); rv = writes ? imap.SelectMailbox(std::string(mailbox), count) : imap.Examine(mailbox, count); int n = atoi(arg); if(rv != 0) { ; } else if(strcmp(command, "count") == 0) { printf("%d\n", count); } else if(strcmp(command, "search") == 0) { std::vector<unsigned> nums; rv = imap.Search(*arg ? arg : "ALL", nums); for(size_t k = 0; rv == 0 && k < nums.size(); k++) { printf("%s%u", k ? " " : "", nums[k]); } if(rv == 0) printf("\n"); } else if(strcmp(command, "header") == 0) { rv = imap.FetchHeader(n, out); if(rv == 0) fwrite(out.data(), 1, out.size(), stdout); } else if(strcmp(command, "body") == 0) { rv = imap.FetchBody(n, out); if(rv == 0) fwrite(out.data(), 1, out.size(), stdout); } else if(strcmp(command, "message") == 0) { rv = imap.FetchMessage(n, out); if(rv == 0) fwrite(out.data(), 1, out.size(), stdout); } else if(strcmp(command, "dates") == 0) { std::string hdr; rv = imap.FetchHeader(n, hdr, out, out2); // The 2007 form if(rv == 0) printf("received: %s\nsent: %s\n", out.c_str(), out2.c_str()); } else if(strcmp(command, "seen") == 0) { char cmd[64]; sprintf(cmd, "STORE %d +FLAGS.SILENT (\\Seen)", n); rv = imap.Command(cmd); } else if(strcmp(command, "delete") == 0) { rv = imap.Delete(n); if(rv == 0) rv = imap.Expunge(); } else { imap.Logout(); Usage(argv[0]); return 1; } } if(rv != 0) return Fail(imap, show_log); imap.Logout(); if(show_log) printf("%s", imap.ProtoString().c_str()); return 0; } // ----------------------------------------------------------- // // ------------------------------- // // --------- End of File --------- // // ------------------------------- //
Modern C++ (C++20)
examples_modern/socket/imap_client/modern.cpp 55 lines
#include <algorithm> #include <iostream> #include <string> #include <vector> #include "../common/modern_net.h" #include "gxsimap.h" using namespace modern_net; int main(int argc, char **argv) { SocketLibrary lib; FakeServer fake; gxsIMAPClient imap; imap.SetTimeout(10); const bool real = argc > 3; std::string user = real ? argv[2] : "user", pass = real ? argv[3] : "secret"; int rv; if(real) { rv = imap.Connect(argv[1]); // TLS, port 993 } else { fake.send("* OK IMAP4rev1 ready\r\n") .reply("* CAPABILITY IMAP4rev1 IDLE UIDPLUS\r\nA0001 OK done\r\n") .reply("A0002 OK LOGIN completed\r\n") .reply("* 3 EXISTS\r\n* 0 RECENT\r\nA0003 OK [READ-ONLY] EXAMINE completed\r\n") .reply("* SEARCH 1 3\r\nA0004 OK SEARCH completed\r\n") .reply("* BYE\r\nA0005 OK LOGOUT completed\r\n"); int port = fake.start(); imap.AllowPlainLogin(); // Local test only rv = imap.ConnectClient("127.0.0.1", port, 0); } if(rv != 0) { std::cout << "Connect failed: " << imap.IMAPExceptionMessage() << "\n"; return 1; } std::vector<std::string> caps; imap.Capability(caps); bool idle = std::ranges::find(caps, "IDLE") != caps.end(); // C++20 ranges std::cout << caps.size() << " capabilities, IDLE " << (idle ? "supported" : "not supported") << "\n"; if(imap.Login(user, pass) != 0) { std::cout << "Login failed: " << imap.IMAPExceptionMessage() << "\n"; return 1; } int count = 0; if(imap.SelectMailbox("INBOX", count, 1) == 0) // 1: read only (EXAMINE) std::cout << "INBOX holds " << count << " messages\n"; gxString numbers; if(imap.Search("UNSEEN", numbers) == 0) std::cout << "Unseen messages: " << numbers.c_str() << "\n"; imap.Logout(); fake.join(); return 0; } // ----------------------------------------------------------- // // ------------------------------- // // --------- End of File --------- // // ------------------------------- //
examples_modern/socket/common/modern_net.h 142 lines
#ifndef MODERN_NET_H #define MODERN_NET_H #include <chrono> #include <cstdio> #include <string> #include <thread> #include <vector> #if !defined(_WIN32) #include <arpa/inet.h> #include <csignal> #endif #include "gxsocket.h" namespace modern_net { inline void ignore_sigpipe() { #if !defined(_WIN32) std::signal(SIGPIPE, SIG_IGN); #endif } class SocketLibrary { // RAII for Winsock and friends public: SocketLibrary() { ok_ = probe_.InitSocketLibrary() == 0; } ~SocketLibrary() { probe_.ReleaseSocketLibrary(); } SocketLibrary(const SocketLibrary &) = delete; SocketLibrary &operator=(const SocketLibrary &) = delete; explicit operator bool() const { return ok_; } private: gxSocket probe_; bool ok_ = false; }; inline int bound_port(gxSocket &s) // After Bind() to port 0 { if(s.GetSockName() < 0) return -1; return int(ntohs(s.sin.sin_port)); } // Opens a listening socket on 127.0.0.1 and a free port. Returns the // port or -1. inline int listen_loopback(gxSocket &s, int backlog = 5) { if(s.InitSocket(SOCK_STREAM, 0, const_cast<char *>("127.0.0.1")) < 0) return -1; if(s.Bind() < 0 || s.Listen(backlog) < 0) return -1; return bound_port(s); } class FakeServer { public: enum class Kind { Send, Sleep, ReadLine, ReadHeader, ReadData, DataListen, DataSend }; struct Step { Kind kind; std::string data; }; FakeServer &send(std::string s) { steps_.push_back({Kind::Send, std::move(s)}); return *this; } FakeServer &sleep(int ms) { steps_.push_back({Kind::Sleep, std::to_string(ms)}); return *this; } FakeServer &read_line() { steps_.push_back({Kind::ReadLine, {}}); return *this; } FakeServer &read_header() { steps_.push_back({Kind::ReadHeader, {}}); return *this; } FakeServer &read_data() { steps_.push_back({Kind::ReadData, {}}); return *this; } FakeServer &reply(std::string s) { read_line(); return send(std::move(s)); } FakeServer &data_listen() { steps_.push_back({Kind::DataListen, {}}); return *this; } FakeServer &data_send(std::string s) { steps_.push_back({Kind::DataSend, std::move(s)}); return *this; } // Starts the script; returns the port or -1 int start() { port_ = listen_loopback(listener_, 1); if(port_ > 0) worker_ = std::jthread([this](std::stop_token st) { run(st); }); return port_; } void join() { if(worker_.joinable()) worker_.join(); } const std::string &received() const { return received_; } // After join() ~FakeServer() { join(); } private: bool wait_read(gxSocket &s, gxsSocket_t fd, std::stop_token &st) { for(int i = 0; i < 50 && !st.stop_requested(); i++) // Up to 5 s if(s.ReadSelect(fd, 0, 100000) > 0) return true; return false; } void run(std::stop_token st) { if(!wait_read(listener_, listener_.GetSocket(), st) || listener_.Accept() < 0) { listener_.Close(); return; } gxsSocket_t c = listener_.GetRemoteSocket(); for(const Step &step : steps_) { if(step.kind == Kind::Send) { std::string d = step.data; if(auto p = d.find("%PORT%"); p != std::string::npos) d.replace(p, 6, std::to_string(data_port_ / 256) + "," + std::to_string(data_port_ % 256)); if(listener_.Send(c, d.data(), int(d.size())) < 0) break; } else if(step.kind == Kind::Sleep) { std::this_thread::sleep_for(std::chrono::milliseconds(std::stoi(step.data))); } else if(step.kind == Kind::DataListen) { data_port_ = listen_loopback(data_, 1); } else if(step.kind == Kind::DataSend) { if(wait_read(data_, data_.GetSocket(), st) && data_.Accept() >= 0) { gxsSocket_t d = data_.GetRemoteSocket(); data_.Send(d, step.data.data(), int(step.data.size())); data_.Close(d); } data_.Close(); } else { // One of the reads std::string got; auto ends_with = [&got](std::string_view e) { return got.ends_with(e); }; while(wait_read(listener_, c, st)) { char ch; if(listener_.RawRead(c, &ch, 1) != 1) break; got += ch; if(step.kind == Kind::ReadLine && ch == '\n') break; if(step.kind == Kind::ReadHeader && ends_with("\r\n\r\n")) break; if(step.kind == Kind::ReadData && ends_with("\r\n.\r\n")) break; } received_ += got; if(got.empty()) break; // The client closed } } std::this_thread::sleep_for(std::chrono::milliseconds(50)); listener_.Close(c); listener_.Close(); } gxSocket listener_, data_; std::vector<Step> steps_; std::string received_; int port_ = -1, data_port_ = 0; std::jthread worker_; }; } // namespace modern_net #endif // MODERN_NET_H // ----------------------------------------------------------- // // ------------------------------- // // --------- End of File --------- // // ------------------------------- //
Build and run
cmake -S examples_modern -B build-modern -DCMAKE_CXX_STANDARD=20 cmake --build build-modern --target socket_imap_client ./build-modern/socket_imap_client
Output of the modern program
From run_modern_tests.sh on RHEL 10, GCC 14, C++20.
3 capabilities, IDLE supported INBOX holds 3 messages Unseen messages: 1 3