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++ Primer 标准库vector示例详解

《C++Primer标准库vector示例详解》该文章主要介绍了C++标准库中的vector类型,包括其定义、初始化、成员函数以及常见操作,文章详细解释了如何使用vector来存储和操作对象集合,... 目录3.3标准库Vector定义和初始化vector对象通列表初始化vector对象创建指定数量的元素值

使用Java发送邮件到QQ邮箱的完整指南

《使用Java发送邮件到QQ邮箱的完整指南》在现代软件开发中,邮件发送功能是一个常见的需求,无论是用户注册验证、密码重置,还是系统通知,邮件都是一种重要的通信方式,本文将详细介绍如何使用Java编写程... 目录引言1. 准备工作1.1 获取QQ邮箱的SMTP授权码1.2 添加JavaMail依赖2. 实现

C++实现回文串判断的两种高效方法

《C++实现回文串判断的两种高效方法》文章介绍了两种判断回文串的方法:解法一通过创建新字符串来处理,解法二在原字符串上直接筛选判断,两种方法都使用了双指针法,文中通过代码示例讲解的非常详细,需要的朋友... 目录一、问题描述示例二、解法一:将字母数字连接到新的 string思路代码实现代码解释复杂度分析三、

C++一个数组赋值给另一个数组方式

《C++一个数组赋值给另一个数组方式》文章介绍了三种在C++中将一个数组赋值给另一个数组的方法:使用循环逐个元素赋值、使用标准库函数std::copy或std::memcpy以及使用标准库容器,每种方... 目录C++一个数组赋值给另一个数组循环遍历赋值使用标准库中的函数 std::copy 或 std::

C++使用栈实现括号匹配的代码详解

《C++使用栈实现括号匹配的代码详解》在编程中,括号匹配是一个常见问题,尤其是在处理数学表达式、编译器解析等任务时,栈是一种非常适合处理此类问题的数据结构,能够精确地管理括号的匹配问题,本文将通过C+... 目录引言问题描述代码讲解代码解析栈的状态表示测试总结引言在编程中,括号匹配是一个常见问题,尤其是在

使用C++实现链表元素的反转

《使用C++实现链表元素的反转》反转链表是链表操作中一个经典的问题,也是面试中常见的考题,本文将从思路到实现一步步地讲解如何实现链表的反转,帮助初学者理解这一操作,我们将使用C++代码演示具体实现,同... 目录问题定义思路分析代码实现带头节点的链表代码讲解其他实现方式时间和空间复杂度分析总结问题定义给定

C++初始化数组的几种常见方法(简单易懂)

《C++初始化数组的几种常见方法(简单易懂)》本文介绍了C++中数组的初始化方法,包括一维数组和二维数组的初始化,以及用new动态初始化数组,在C++11及以上版本中,还提供了使用std::array... 目录1、初始化一维数组1.1、使用列表初始化(推荐方式)1.2、初始化部分列表1.3、使用std::

C++ Primer 多维数组的使用

《C++Primer多维数组的使用》本文主要介绍了多维数组在C++语言中的定义、初始化、下标引用以及使用范围for语句处理多维数组的方法,具有一定的参考价值,感兴趣的可以了解一下... 目录多维数组多维数组的初始化多维数组的下标引用使用范围for语句处理多维数组指针和多维数组多维数组严格来说,C++语言没

c++中std::placeholders的使用方法

《c++中std::placeholders的使用方法》std::placeholders是C++标准库中的一个工具,用于在函数对象绑定时创建占位符,本文就来详细的介绍一下,具有一定的参考价值,感兴... 目录1. 基本概念2. 使用场景3. 示例示例 1:部分参数绑定示例 2:参数重排序4. 注意事项5.

使用C++将处理后的信号保存为PNG和TIFF格式

《使用C++将处理后的信号保存为PNG和TIFF格式》在信号处理领域,我们常常需要将处理结果以图像的形式保存下来,方便后续分析和展示,C++提供了多种库来处理图像数据,本文将介绍如何使用stb_ima... 目录1. PNG格式保存使用stb_imagephp_write库1.1 安装和包含库1.2 代码解