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 Plus习题】13.4

大家好,这里是国中之林! ❥前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住分享一下给大家。点击跳转到网站。有兴趣的可以点点进去看看← 问题: 解答: main.cpp #include <iostream>#include "port.h"int main() {Port p1;Port p2("Abc", "Bcc", 30);std::cout <<

C++包装器

包装器 在 C++ 中,“包装器”通常指的是一种设计模式或编程技巧,用于封装其他代码或对象,使其更易于使用、管理或扩展。包装器的概念在编程中非常普遍,可以用于函数、类、库等多个方面。下面是几个常见的 “包装器” 类型: 1. 函数包装器 函数包装器用于封装一个或多个函数,使其接口更统一或更便于调用。例如,std::function 是一个通用的函数包装器,它可以存储任意可调用对象(函数、函数

C++11第三弹:lambda表达式 | 新的类功能 | 模板的可变参数

🌈个人主页: 南桥几晴秋 🌈C++专栏: 南桥谈C++ 🌈C语言专栏: C语言学习系列 🌈Linux学习专栏: 南桥谈Linux 🌈数据结构学习专栏: 数据结构杂谈 🌈数据库学习专栏: 南桥谈MySQL 🌈Qt学习专栏: 南桥谈Qt 🌈菜鸡代码练习: 练习随想记录 🌈git学习: 南桥谈Git 🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈�

【C++】_list常用方法解析及模拟实现

相信自己的力量,只要对自己始终保持信心,尽自己最大努力去完成任何事,就算事情最终结果是失败了,努力了也不留遗憾。💓💓💓 目录   ✨说在前面 🍋知识点一:什么是list? •🌰1.list的定义 •🌰2.list的基本特性 •🌰3.常用接口介绍 🍋知识点二:list常用接口 •🌰1.默认成员函数 🔥构造函数(⭐) 🔥析构函数 •🌰2.list对象

06 C++Lambda表达式

lambda表达式的定义 没有显式模版形参的lambda表达式 [捕获] 前属性 (形参列表) 说明符 异常 后属性 尾随类型 约束 {函数体} 有显式模版形参的lambda表达式 [捕获] <模版形参> 模版约束 前属性 (形参列表) 说明符 异常 后属性 尾随类型 约束 {函数体} 含义 捕获:包含零个或者多个捕获符的逗号分隔列表 模板形参:用于泛型lambda提供个模板形参的名

6.1.数据结构-c/c++堆详解下篇(堆排序,TopK问题)

上篇:6.1.数据结构-c/c++模拟实现堆上篇(向下,上调整算法,建堆,增删数据)-CSDN博客 本章重点 1.使用堆来完成堆排序 2.使用堆解决TopK问题 目录 一.堆排序 1.1 思路 1.2 代码 1.3 简单测试 二.TopK问题 2.1 思路(求最小): 2.2 C语言代码(手写堆) 2.3 C++代码(使用优先级队列 priority_queue)

【C++高阶】C++类型转换全攻略:深入理解并高效应用

📝个人主页🌹:Eternity._ ⏩收录专栏⏪:C++ “ 登神长阶 ” 🤡往期回顾🤡:C++ 智能指针 🌹🌹期待您的关注 🌹🌹 ❀C++的类型转换 📒1. C语言中的类型转换📚2. C++强制类型转换⛰️static_cast🌞reinterpret_cast⭐const_cast🍁dynamic_cast 📜3. C++强制类型转换的原因📝

C++——stack、queue的实现及deque的介绍

目录 1.stack与queue的实现 1.1stack的实现  1.2 queue的实现 2.重温vector、list、stack、queue的介绍 2.1 STL标准库中stack和queue的底层结构  3.deque的简单介绍 3.1为什么选择deque作为stack和queue的底层默认容器  3.2 STL中对stack与queue的模拟实现 ①stack模拟实现

c++的初始化列表与const成员

初始化列表与const成员 const成员 使用const修饰的类、结构、联合的成员变量,在类对象创建完成前一定要初始化。 不能在构造函数中初始化const成员,因为执行构造函数时,类对象已经创建完成,只有类对象创建完成才能调用成员函数,构造函数虽然特殊但也是成员函数。 在定义const成员时进行初始化,该语法只有在C11语法标准下才支持。 初始化列表 在构造函数小括号后面,主要用于给

2024/9/8 c++ smart

1.通过自己编写的class来实现unique_ptr指针的功能 #include <iostream> using namespace std; template<class T> class unique_ptr { public:         //无参构造函数         unique_ptr();         //有参构造函数         unique_ptr(