C/C++:libcurl smtp 邮件客户端(MUA)

2024-03-25 16:58

本文主要是介绍C/C++:libcurl smtp 邮件客户端(MUA),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

C/C++:libcurl smtp 邮件客户端(MUA)

最近在研究关于邮件的一些东西,需要实现个自己的邮件客户端,也就是类似于Foxmail那样的东西。

网上找了下感觉使用libcurl比较便捷靠谱(当然,还有esmtp等库)。

先放几个主要的libcurl官方的Sample,然后相关内容我晚点再整理下。

Sample 1:(最常用的最简单的,模拟MUA发送邮件到MTA)

/****************************************************************************                                  _   _ ____  _*  Project                     ___| | | |  _ \| |*                             / __| | | | |_) | |*                            | (__| |_| |  _ <| |___*                             \___|\___/|_| \_\_____|** Copyright (C) 1998 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al.** This software is licensed as described in the file COPYING, which* you should have received as part of this distribution. The terms* are also available at https://curl.haxx.se/docs/copyright.html.** You may opt to use, copy, modify, merge, publish, distribute and/or sell* copies of the Software, and permit persons to whom the Software is* furnished to do so, under the terms of the COPYING file.** This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY* KIND, either express or implied.****************************************************************************//* <DESC>* Send e-mail with SMTP* </DESC>*/#include <stdio.h>
#include <string.h>
#include <curl/curl.h>/** For an SMTP example using the multi interface please see smtp-multi.c.*//* The libcurl options want plain addresses, the viewable headers in the mail* can very well get a full name as well.*/
#define FROM_ADDR    "<sender@example.org>"
#define TO_ADDR      "<addressee@example.net>"
#define CC_ADDR      "<info@example.org>"#define FROM_MAIL "Sender Person " FROM_ADDR
#define TO_MAIL   "A Receiver " TO_ADDR
#define CC_MAIL   "John CC Smith " CC_ADDRstatic const char *payload_text[] = {"Date: Mon, 29 Nov 2010 21:54:29 +1100\r\n","To: " TO_MAIL "\r\n","From: " FROM_MAIL "\r\n","Cc: " CC_MAIL "\r\n","Message-ID: <dcd7cb36-11db-487a-9f3a-e652a9458efd@""rfcpedant.example.org>\r\n","Subject: SMTP example message\r\n","\r\n", /* empty line to divide headers from body, see RFC5322 */"The body of the message starts here.\r\n","\r\n","It could be a lot of lines, could be MIME encoded, whatever.\r\n","Check RFC5322.\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) {/* This is the URL for your mailserver */curl_easy_setopt(curl, CURLOPT_URL, "smtp://mail.example.com");/* Note that this option isn't strictly required, omitting it will result* in libcurl sending the MAIL FROM command with empty sender data. All* autoresponses should have an empty reverse-path, and should be directed* to the address in the reverse-path which triggered them. Otherwise,* they could cause an endless loop. See RFC 5321 Section 4.5.5 for more* details.*/curl_easy_setopt(curl, CURLOPT_MAIL_FROM, FROM_ADDR);/* Add two recipients, in this particular case they correspond to the* To: and Cc: addressees in the header, but they could be any kind of* recipient. */recipients = curl_slist_append(recipients, TO_ADDR);recipients = curl_slist_append(recipients, CC_ADDR);curl_easy_setopt(curl, CURLOPT_MAIL_RCPT, recipients);/* We're using a callback function to specify the payload (the headers and* body of the message). You could just use the CURLOPT_READDATA option to* specify a FILE pointer to read from. */curl_easy_setopt(curl, CURLOPT_READFUNCTION, payload_source);curl_easy_setopt(curl, CURLOPT_READDATA, &upload_ctx);curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L);/* Send the message */res = curl_easy_perform(curl);/* Check for errors */if(res != CURLE_OK)fprintf(stderr, "curl_easy_perform() failed: %s\n",curl_easy_strerror(res));/* Free the list of recipients */curl_slist_free_all(recipients);/* curl won't send the QUIT command until you call cleanup, so you should* be able to re-use this connection for additional messages (setting* CURLOPT_MAIL_FROM and CURLOPT_MAIL_RCPT as required, and calling* curl_easy_perform() again. It may not be a good idea to keep the* connection open for a very long time though (more than a few minutes* may result in the server timing out the connection), and you do want to* clean up in the end.*/curl_easy_cleanup(curl);}return (int)res;
}

Sample 2:(+SSL)

/****************************************************************************                                  _   _ ____  _*  Project                     ___| | | |  _ \| |*                             / __| | | | |_) | |*                            | (__| |_| |  _ <| |___*                             \___|\___/|_| \_\_____|** Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al.** This software is licensed as described in the file COPYING, which* you should have received as part of this distribution. The terms* are also available at https://curl.haxx.se/docs/copyright.html.** You may opt to use, copy, modify, merge, publish, distribute and/or sell* copies of the Software, and permit persons to whom the Software is* furnished to do so, under the terms of the COPYING file.** This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY* KIND, either express or implied.****************************************************************************//* <DESC>* SMTP example using SSL* </DESC>*/#include <stdio.h>
#include <string.h>
#include <curl/curl.h>/* This is a simple example showing how to send mail using libcurl's SMTP* capabilities. It builds on the smtp-mail.c example to add authentication* and, more importantly, transport security to protect the authentication* details from being snooped.** Note that this example requires libcurl 7.20.0 or above.*/#define FROM    "<sender@example.org>"
#define TO      "<addressee@example.net>"
#define CC      "<info@example.org>"static const char *payload_text[] = {"Date: Mon, 29 Nov 2010 21:54:29 +1100\r\n","To: " TO "\r\n","From: " FROM " (Example User)\r\n","Cc: " CC " (Another example User)\r\n","Message-ID: <dcd7cb36-11db-487a-9f3a-e652a9458efd@""rfcpedant.example.org>\r\n","Subject: SMTP SSL example message\r\n","\r\n", /* empty line to divide headers from body, see RFC5322 */"The body of the message starts here.\r\n","\r\n","It could be a lot of lines, could be MIME encoded, whatever.\r\n","Check RFC5322.\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) {/* Set username and password */curl_easy_setopt(curl, CURLOPT_USERNAME, "user");curl_easy_setopt(curl, CURLOPT_PASSWORD, "secret");/* This is the URL for your mailserver. Note the use of smtps:// rather* than smtp:// to request a SSL based connection. */curl_easy_setopt(curl, CURLOPT_URL, "smtps://mainserver.example.net");/* If you want to connect to a site who isn't using a certificate that is* signed by one of the certs in the CA bundle you have, you can skip the* verification of the server's certificate. This makes the connection* A LOT LESS SECURE.** If you have a CA cert for the server stored someplace else than in the* default bundle, then the CURLOPT_CAPATH option might come handy for* you. */
#ifdef SKIP_PEER_VERIFICATIONcurl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
#endif/* If the site you're connecting to uses a different host name that what* they have mentioned in their server certificate's commonName (or* subjectAltName) fields, libcurl will refuse to connect. You can skip* this check, but this will make the connection less secure. */
#ifdef SKIP_HOSTNAME_VERIFICATIONcurl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);
#endif/* Note that this option isn't strictly required, omitting it will result* in libcurl sending the MAIL FROM command with empty sender data. All* autoresponses should have an empty reverse-path, and should be directed* to the address in the reverse-path which triggered them. Otherwise,* they could cause an endless loop. See RFC 5321 Section 4.5.5 for more* details.*/curl_easy_setopt(curl, CURLOPT_MAIL_FROM, FROM);/* Add two recipients, in this particular case they correspond to the* To: and Cc: addressees in the header, but they could be any kind of* recipient. */recipients = curl_slist_append(recipients, TO);recipients = curl_slist_append(recipients, CC);curl_easy_setopt(curl, CURLOPT_MAIL_RCPT, recipients);/* We're using a callback function to specify the payload (the headers and* body of the message). You could just use the CURLOPT_READDATA option to* specify a FILE pointer to read from. */curl_easy_setopt(curl, CURLOPT_READFUNCTION, payload_source);curl_easy_setopt(curl, CURLOPT_READDATA, &upload_ctx);curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L);/* Since the traffic will be encrypted, it is very useful to turn on debug* information within libcurl to see what is happening during the* transfer */curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);/* Send the message */res = curl_easy_perform(curl);/* Check for errors */if(res != CURLE_OK)fprintf(stderr, "curl_easy_perform() failed: %s\n",curl_easy_strerror(res));/* Free the list of recipients */curl_slist_free_all(recipients);/* Always cleanup */curl_easy_cleanup(curl);}return (int)res;
}

Sample 3:(+TLS)

/****************************************************************************                                  _   _ ____  _*  Project                     ___| | | |  _ \| |*                             / __| | | | |_) | |*                            | (__| |_| |  _ <| |___*                             \___|\___/|_| \_\_____|** Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al.** This software is licensed as described in the file COPYING, which* you should have received as part of this distribution. The terms* are also available at https://curl.haxx.se/docs/copyright.html.** You may opt to use, copy, modify, merge, publish, distribute and/or sell* copies of the Software, and permit persons to whom the Software is* furnished to do so, under the terms of the COPYING file.** This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY* KIND, either express or implied.****************************************************************************//* <DESC>* SMTP example using TLS* </DESC>*/#include <stdio.h>
#include <string.h>
#include <curl/curl.h>/* This is a simple example showing how to send mail using libcurl's SMTP* capabilities. It builds on the smtp-mail.c example to add authentication* and, more importantly, transport security to protect the authentication* details from being snooped.** Note that this example requires libcurl 7.20.0 or above.*/#define FROM    "<sender@example.org>"
#define TO      "<addressee@example.net>"
#define CC      "<info@example.org>"static const char *payload_text[] = {"Date: Mon, 29 Nov 2010 21:54:29 +1100\r\n","To: " TO "\r\n","From: " FROM " (Example User)\r\n","Cc: " CC " (Another example User)\r\n","Message-ID: <dcd7cb36-11db-487a-9f3a-e652a9458efd@""rfcpedant.example.org>\r\n","Subject: SMTP TLS example message\r\n","\r\n", /* empty line to divide headers from body, see RFC5322 */"The body of the message starts here.\r\n","\r\n","It could be a lot of lines, could be MIME encoded, whatever.\r\n","Check RFC5322.\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) {/* Set username and password */curl_easy_setopt(curl, CURLOPT_USERNAME, "user");curl_easy_setopt(curl, CURLOPT_PASSWORD, "secret");/* This is the URL for your mailserver. Note the use of port 587 here,* instead of the normal SMTP port (25). Port 587 is commonly used for* secure mail submission (see RFC4403), but you should use whatever* matches your server configuration. */curl_easy_setopt(curl, CURLOPT_URL, "smtp://mainserver.example.net:587");/* In this example, we'll start with a plain text connection, and upgrade* to Transport Layer Security (TLS) using the STARTTLS command. Be careful* of using CURLUSESSL_TRY here, because if TLS upgrade fails, the transfer* will continue anyway - see the security discussion in the libcurl* tutorial for more details. */curl_easy_setopt(curl, CURLOPT_USE_SSL, (long)CURLUSESSL_ALL);/* If your server doesn't have a valid certificate, then you can disable* part of the Transport Layer Security protection by setting the* CURLOPT_SSL_VERIFYPEER and CURLOPT_SSL_VERIFYHOST options to 0 (false).*   curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);*   curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);* That is, in general, a bad idea. It is still better than sending your* authentication details in plain text though.  Instead, you should get* the issuer certificate (or the host certificate if the certificate is* self-signed) and add it to the set of certificates that are known to* libcurl using CURLOPT_CAINFO and/or CURLOPT_CAPATH. See docs/SSLCERTS* for more information. */curl_easy_setopt(curl, CURLOPT_CAINFO, "/path/to/certificate.pem");/* Note that this option isn't strictly required, omitting it will result* in libcurl sending the MAIL FROM command with empty sender data. All* autoresponses should have an empty reverse-path, and should be directed* to the address in the reverse-path which triggered them. Otherwise,* they could cause an endless loop. See RFC 5321 Section 4.5.5 for more* details.*/curl_easy_setopt(curl, CURLOPT_MAIL_FROM, FROM);/* Add two recipients, in this particular case they correspond to the* To: and Cc: addressees in the header, but they could be any kind of* recipient. */recipients = curl_slist_append(recipients, TO);recipients = curl_slist_append(recipients, CC);curl_easy_setopt(curl, CURLOPT_MAIL_RCPT, recipients);/* We're using a callback function to specify the payload (the headers and* body of the message). You could just use the CURLOPT_READDATA option to* specify a FILE pointer to read from. */curl_easy_setopt(curl, CURLOPT_READFUNCTION, payload_source);curl_easy_setopt(curl, CURLOPT_READDATA, &upload_ctx);curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L);/* Since the traffic will be encrypted, it is very useful to turn on debug* information within libcurl to see what is happening during the transfer.*/curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);/* Send the message */res = curl_easy_perform(curl);/* Check for errors */if(res != CURLE_OK)fprintf(stderr, "curl_easy_perform() failed: %s\n",curl_easy_strerror(res));/* Free the list of recipients */curl_slist_free_all(recipients);/* Always cleanup */curl_easy_cleanup(curl);}return (int)res;
}

官方资料:

1)https://curl.haxx.se/libcurl/c/example.html
2)https://curl.haxx.se/libcurl/c/smtp-mail.html
3)https://curl.haxx.se/libcurl/c/smtp-ssl.html
4)https://curl.haxx.se/libcurl/c/smtp-tls.html

源文件:

1)https://raw.githubusercontent.com/curl/curl/master/docs/examples/smtp-mail.c
2)https://raw.githubusercontent.com/curl/curl/master/docs/examples/smtp-ssl.c
3)https://raw.githubusercontent.com/curl/curl/master/docs/examples/smtp-tls.c

资料搬运工~

今天晚点我再整理下具体遇到的问题~

这篇关于C/C++:libcurl smtp 邮件客户端(MUA)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/845640

相关文章

C++使用printf语句实现进制转换的示例代码

《C++使用printf语句实现进制转换的示例代码》在C语言中,printf函数可以直接实现部分进制转换功能,通过格式说明符(formatspecifier)快速输出不同进制的数值,下面给大家分享C+... 目录一、printf 原生支持的进制转换1. 十进制、八进制、十六进制转换2. 显示进制前缀3. 指

C++中初始化二维数组的几种常见方法

《C++中初始化二维数组的几种常见方法》本文详细介绍了在C++中初始化二维数组的不同方式,包括静态初始化、循环、全部为零、部分初始化、std::array和std::vector,以及std::vec... 目录1. 静态初始化2. 使用循环初始化3. 全部初始化为零4. 部分初始化5. 使用 std::a

C++ vector的常见用法超详细讲解

《C++vector的常见用法超详细讲解》:本文主要介绍C++vector的常见用法,包括C++中vector容器的定义、初始化方法、访问元素、常用函数及其时间复杂度,通过代码介绍的非常详细,... 目录1、vector的定义2、vector常用初始化方法1、使编程用花括号直接赋值2、使用圆括号赋值3、ve

如何高效移除C++关联容器中的元素

《如何高效移除C++关联容器中的元素》关联容器和顺序容器有着很大不同,关联容器中的元素是按照关键字来保存和访问的,而顺序容器中的元素是按它们在容器中的位置来顺序保存和访问的,本文介绍了如何高效移除C+... 目录一、简介二、移除给定位置的元素三、移除与特定键值等价的元素四、移除满足特android定条件的元

Python获取C++中返回的char*字段的两种思路

《Python获取C++中返回的char*字段的两种思路》有时候需要获取C++函数中返回来的不定长的char*字符串,本文小编为大家找到了两种解决问题的思路,感兴趣的小伙伴可以跟随小编一起学习一下... 有时候需要获取C++函数中返回来的不定长的char*字符串,目前我找到两种解决问题的思路,具体实现如下:

C++ Sort函数使用场景分析

《C++Sort函数使用场景分析》sort函数是algorithm库下的一个函数,sort函数是不稳定的,即大小相同的元素在排序后相对顺序可能发生改变,如果某些场景需要保持相同元素间的相对顺序,可使... 目录C++ Sort函数详解一、sort函数调用的两种方式二、sort函数使用场景三、sort函数排序

Java调用C++动态库超详细步骤讲解(附源码)

《Java调用C++动态库超详细步骤讲解(附源码)》C语言因其高效和接近硬件的特性,时常会被用在性能要求较高或者需要直接操作硬件的场合,:本文主要介绍Java调用C++动态库的相关资料,文中通过代... 目录一、直接调用C++库第一步:动态库生成(vs2017+qt5.12.10)第二步:Java调用C++

C/C++错误信息处理的常见方法及函数

《C/C++错误信息处理的常见方法及函数》C/C++是两种广泛使用的编程语言,特别是在系统编程、嵌入式开发以及高性能计算领域,:本文主要介绍C/C++错误信息处理的常见方法及函数,文中通过代码介绍... 目录前言1. errno 和 perror()示例:2. strerror()示例:3. perror(

C++变换迭代器使用方法小结

《C++变换迭代器使用方法小结》本文主要介绍了C++变换迭代器使用方法小结,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧... 目录1、源码2、代码解析代码解析:transform_iterator1. transform_iterat

详解C++中类的大小决定因数

《详解C++中类的大小决定因数》类的大小受多个因素影响,主要包括成员变量、对齐方式、继承关系、虚函数表等,下面就来介绍一下,具有一定的参考价值,感兴趣的可以了解一下... 目录1. 非静态数据成员示例:2. 数据对齐(Padding)示例:3. 虚函数(vtable 指针)示例:4. 继承普通继承虚继承5.