Malek
Malek

Reputation: 19

how to send an email using libcurl

I'm able to send an email to my gmail successfully, but it's sending an empty message and not able to send contain message , anyway the code I'm using is as follows:

#include <stdio.h>
#include <string.h>
#include <curl/curl.h>
#define FROM    "<[email protected]>"
#define TO      "<[email protected]>"

static const char* payload_text[] = 
{
  "To: " TO "\r\n",
  "From: " FROM "\r\n",
  "Subject: SMTP TLS example message\r\n",
  "Contain: Helllo\r\n",
  NULL
};

struct upload_status {
    int lines_read;
};

static size_t payload_source(void* ptr, size_t size, size_t nmemb, void* userp)
{
    struct upload_status* upload_ctx = (struct upload_status*)userp;
    const char* data;

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

    data = payload_text[upload_ctx->lines_read];

    if (data) {
        size_t len = strlen(data);
        memcpy(ptr, data, len);
        upload_ctx->lines_read++;

        return len;
    }

    return 0;
}

int main(void)
{
    CURL* curl;
    CURLcode res = CURLE_OK;
    struct curl_slist* recipients = NULL;
    struct upload_status upload_ctx;
    upload_ctx.lines_read = 0;
    curl = curl_easy_init();
    if (curl) {
        curl_easy_setopt(curl, CURLOPT_USERNAME, "[email protected]");
        curl_easy_setopt(curl, CURLOPT_PASSWORD, "xxxxxxxx");
        curl_easy_setopt(curl, CURLOPT_URL, "smtp://smtp.gmail.com:587");
        curl_easy_setopt(curl, CURLOPT_USE_SSL, (long)CURLUSESSL_ALL);
        curl_easy_setopt(curl, CURLOPT_MAIL_FROM, FROM);
        recipients = curl_slist_append(recipients, TO);
        curl_easy_setopt(curl, CURLOPT_MAIL_RCPT, recipients);
        curl_easy_setopt(curl, CURLOPT_READFUNCTION, payload_source);
        curl_easy_setopt(curl, CURLOPT_READDATA, &upload_ctx);
        curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L);
        curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
        res = curl_easy_perform(curl);

       if (res != CURLE_OK)
        fprintf(stderr, "curl_easy_perform() failed: %s\n",
            curl_easy_strerror(res));

        curl_slist_free_all(recipients);

        curl_easy_cleanup(curl);
    }
    return (int)res;
}

How to fix this ? I have no acquaintance with this library,and the only thing I can receive is the subject, Thanks if anyone can help

Upvotes: 0

Views: 298

Answers (1)

john
john

Reputation: 87932

static const char* payload_text[] = 
{
  "To: " TO "\r\n",
  "From: " FROM "\r\n",
  "Subject: SMTP TLS example message\r\n",
  "Contain: Helllo\r\n",
  NULL
};

should be something like

static const char* payload_text[] = 
{
  "To: " TO "\r\n",
  "From: " FROM "\r\n",
  "Subject: SMTP TLS example message\r\n",
  "\r\n",
  "Helllo\r\n",
  NULL
};

That is Contain: is wrong, and there should be a blank line between the headers and the message.

Email format is described here.

Upvotes: 1

Related Questions