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

相关文章

Java中使用Java Mail实现邮件服务功能示例

《Java中使用JavaMail实现邮件服务功能示例》:本文主要介绍Java中使用JavaMail实现邮件服务功能的相关资料,文章还提供了一个发送邮件的示例代码,包括创建参数类、邮件类和执行结... 目录前言一、历史背景二编程、pom依赖三、API说明(一)Session (会话)(二)Message编程客

C++中使用vector存储并遍历数据的基本步骤

《C++中使用vector存储并遍历数据的基本步骤》C++标准模板库(STL)提供了多种容器类型,包括顺序容器、关联容器、无序关联容器和容器适配器,每种容器都有其特定的用途和特性,:本文主要介绍C... 目录(1)容器及简要描述‌php顺序容器‌‌关联容器‌‌无序关联容器‌(基于哈希表):‌容器适配器‌:(

Python手搓邮件发送客户端

《Python手搓邮件发送客户端》这篇文章主要为大家详细介绍了如何使用Python手搓邮件发送客户端,支持发送邮件,附件,定时发送以及个性化邮件正文,感兴趣的可以了解下... 目录1. 简介2.主要功能2.1.邮件发送功能2.2.个性签名功能2.3.定时发送功能2. 4.附件管理2.5.配置加载功能2.6.

C++中实现调试日志输出

《C++中实现调试日志输出》在C++编程中,调试日志对于定位问题和优化代码至关重要,本文将介绍几种常用的调试日志输出方法,并教你如何在日志中添加时间戳,希望对大家有所帮助... 目录1. 使用 #ifdef _DEBUG 宏2. 加入时间戳:精确到毫秒3.Windows 和 MFC 中的调试日志方法MFC

解决Cron定时任务中Pytest脚本无法发送邮件的问题

《解决Cron定时任务中Pytest脚本无法发送邮件的问题》文章探讨解决在Cron定时任务中运行Pytest脚本时邮件发送失败的问题,先优化环境变量,再检查Pytest邮件配置,接着配置文件确保SMT... 目录引言1. 环境变量优化:确保Cron任务可以正确执行解决方案:1.1. 创建一个脚本1.2. 修

Redis连接失败:客户端IP不在白名单中的问题分析与解决方案

《Redis连接失败:客户端IP不在白名单中的问题分析与解决方案》在现代分布式系统中,Redis作为一种高性能的内存数据库,被广泛应用于缓存、消息队列、会话存储等场景,然而,在实际使用过程中,我们可能... 目录一、问题背景二、错误分析1. 错误信息解读2. 根本原因三、解决方案1. 将客户端IP添加到Re

深入理解C++ 空类大小

《深入理解C++空类大小》本文主要介绍了C++空类大小,规定空类大小为1字节,主要是为了保证对象的唯一性和可区分性,满足数组元素地址连续的要求,下面就来了解一下... 目录1. 保证对象的唯一性和可区分性2. 满足数组元素地址连续的要求3. 与C++的对象模型和内存管理机制相适配查看类对象内存在C++中,规

在 VSCode 中配置 C++ 开发环境的详细教程

《在VSCode中配置C++开发环境的详细教程》本文详细介绍了如何在VisualStudioCode(VSCode)中配置C++开发环境,包括安装必要的工具、配置编译器、设置调试环境等步骤,通... 目录如何在 VSCode 中配置 C++ 开发环境:详细教程1. 什么是 VSCode?2. 安装 VSCo

Django中使用SMTP实现邮件发送功能

《Django中使用SMTP实现邮件发送功能》在Django中使用SMTP发送邮件是一个常见的需求,通常用于发送用户注册确认邮件、密码重置邮件等,下面我们来看看如何在Django中配置S... 目录1. 配置 Django 项目以使用 SMTP2. 创建 Django 应用3. 添加应用到项目设置4. 创建

SpringBoot实现websocket服务端及客户端的详细过程

《SpringBoot实现websocket服务端及客户端的详细过程》文章介绍了WebSocket通信过程、服务端和客户端的实现,以及可能遇到的问题及解决方案,感兴趣的朋友一起看看吧... 目录一、WebSocket通信过程二、服务端实现1.pom文件添加依赖2.启用Springboot对WebSocket