Advertisement
bra_fsn_hu

curl smtp example

Nov 25th, 2014
655
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.03 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <curl/curl.h>
  4. #define FROM    "<sender@example.org>"
  5. #define TO      "<recipient@example.org>"
  6.  
  7. static const char *payload_text[] = {
  8.   "Date: Mon, 29 Nov 2010 21:54:29 +1100\n",
  9.   "To: " TO "\n",
  10.   "From: " FROM "(Example User)\n",
  11.   "Message-ID: <dcd7cb36-11db-487a-9f3a-e652a9458efd@rfcpedant.example.org>\n",
  12.   "Subject: SMTP example message\n",
  13.   "\n", /* empty line to divide headers from body, see RFC5322 */
  14.   ".The body of the message starts here.\n",
  15.   "\n",
  16.   ".\n",
  17.   "It could be a lot of lines, could be MIME encoded, whatever.\n",
  18.   "Check RFC5322.\n",
  19.   NULL
  20. };
  21.  
  22. struct upload_status {
  23.   int lines_read;
  24. };
  25.  
  26. static size_t payload_source(void *ptr, size_t size, size_t nmemb, void *userp)
  27. {
  28.   struct upload_status *upload_ctx = (struct upload_status *)userp;
  29.   const char *data;
  30.  
  31.   if((size == 0) || (nmemb == 0) || ((size*nmemb) < 1)) {
  32.     return 0;
  33.   }
  34.  
  35.   data = payload_text[upload_ctx->lines_read];
  36.  
  37.   if(data) {
  38.     size_t len = strlen(data);
  39.     memcpy(ptr, data, len);
  40.     upload_ctx->lines_read++;
  41.  
  42.     return len;
  43.   }
  44.  
  45.   return 0;
  46. }
  47.  
  48. int main(void)
  49. {
  50.   CURL *curl;
  51.   CURLcode res = CURLE_OK;
  52.   struct curl_slist *recipients = NULL;
  53.   struct upload_status upload_ctx;
  54.  
  55.   upload_ctx.lines_read = 0;
  56.  
  57.   curl = curl_easy_init();
  58.   if(curl) {
  59.     curl_easy_setopt(curl, CURLOPT_URL, "smtp://localhost");
  60.     curl_easy_setopt(curl, CURLOPT_MAIL_FROM, FROM);
  61.     recipients = curl_slist_append(recipients, TO);
  62.     curl_easy_setopt(curl, CURLOPT_MAIL_RCPT, recipients);
  63.     curl_easy_setopt(curl, CURLOPT_READFUNCTION, payload_source);
  64.     curl_easy_setopt(curl, CURLOPT_READDATA, &upload_ctx);
  65.     curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L);
  66.     curl_easy_setopt(curl, CURLOPT_CRLF, 1L);
  67.     res = curl_easy_perform(curl);
  68.     if(res != CURLE_OK)
  69.       fprintf(stderr, "curl_easy_perform() failed: %s\n",
  70.               curl_easy_strerror(res));
  71.     curl_slist_free_all(recipients);
  72.     curl_easy_cleanup(curl);
  73.   }
  74.  
  75.   return (int)res;
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement