Source Code File 07-03_mailsend.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <curl/curl.h>

const char *message[] = {
    "Date: Sat, 16 Oct 2021 14:00:00 +800\r\n",
    "To: joe_user@mail.com\r\n",
    "From: somebody@site.com\r\n",
    "Subject: Test message\r\n",
    "\r\n",    /* blank line */
    "Hello! This is a test\r\n",
    (char *)NULL
};

struct up_stat {
    int lines_read;
};

static size_t paysrc(
    void *ptr,
    size_t size,
    size_t nmemb,
    void *userp)
{
    struct up_stat *upcount;
    const char *data;
    size_t len;

    upcount = (struct up_stat *)userp;

    if( (size==0) || (nmemb==0) || ((size*nmemb)<1))
    {
        return(0);
    }

    data = message[upcount->lines_read];
    if( data!=NULL )
    {
        len = strlen(data);
        memcpy(ptr, data, len);
        upcount->lines_read++;
        return(len);
    }

    return(0);
}

int main()
{
    const char address[] = "smtp://127.0.0.0";
    struct up_stat upcount;
    struct curl_slist *rec = NULL;
    CURL *curl;
    CURLcode r;

    upcount.lines_read = 0;

    curl = curl_easy_init();
    if( curl==NULL )
    {
        fprintf(stderr,"Unable to curl\n");
        exit(1);
    }

    curl_easy_setopt(curl,
        CURLOPT_URL, address);
    curl_easy_setopt(curl,
        CURLOPT_USERNAME, "user");
    curl_easy_setopt(curl,
        CURLOPT_PASSWORD, "password");
    curl_easy_setopt(curl,
        CURLOPT_MAIL_FROM, "<somebody@site.com>");
    rec=curl_slist_append(rec,"<joe_user@mail.com>");
    curl_easy_setopt(curl,
        CURLOPT_MAIL_RCPT, rec);
    curl_easy_setopt(curl,
        CURLOPT_READFUNCTION, paysrc);
    curl_easy_setopt(curl,
        CURLOPT_READDATA, &upcount);
    curl_easy_setopt(curl,
        CURLOPT_UPLOAD, 1L);

    r = curl_easy_perform(curl);
    if( r!=CURLE_OK )
    {
        fprintf(stderr,"Curl failed: %s\n",
            curl_easy_strerror(r));
        exit(1);
    }
                
    curl_easy_cleanup(curl);

    return(0);
}

Notes

* The addresses, username, and password in this code are placeholders.

* Wide version of this code (statements not split)