在 C++ 中发送电子邮件:库和工具概述
发送电子邮件是许多应用程序的基本任务之一:从监控系统到用户通知。在 C++ 中,此任务可以通过多种方式解决——从直接使用套接字到支持加密、MIME 和附件的强大库。在本文中,我们将介绍用于在 C++ 中发送电子邮件的最佳工具,并展示代码示例。
为什么选择 C++ 发送电子邮件?
C++ 可以完全控制网络连接、性能和内存。然而,C++ 标准库不包含用于处理邮件协议(SMTP、POP3、IMAP)的内置工具。因此,开发者要么使用第三方库,要么通过套接字手动实现协议。我们将专注于现成的解决方案,这些方案可以节省时间并确保稳定性。
用于在 C++ 中发送电子邮件的主要库
- libcurl — 最流行的跨平台数据传输库。支持 SMTP、带 SSL/TLS 的 SMTP、身份验证和 MIME 附件。
- VMime — 专门用于处理电子邮件的库。完全支持 MIME、S/MIME 加密、自定义标头和所有邮件协议。
- c-icap 和 libESMTP — 更底层的库,专注于 SMTP 会话。
- Boost.Asio + 自定义 SMTP 实现 — 适用于希望最小化依赖关系并愿意手动编写协议的人。
在本文中,我们将详细介绍 libcurl,因为它最通用且被广泛使用。
安装 libcurl
要开始使用 libcurl,需要先安装它:
- Linux (Ubuntu/Debian):
sudo apt install libcurl4-openssl-dev - macOS:
brew install curl - Windows: 从 官方网站 下载预编译的二进制文件,或使用 vcpkg:
vcpkg install curl
示例 1:通过 Gmail 发送简单电子邮件 (SSL)
在此示例中,使用 libcurl 通过带有 SSL 加密的 Gmail SMTP 服务器发送邮件。
#include <stdio.h>#include <string.h>#include <curl/curl.h>
int main(void) { CURL *curl; CURLcode res;
curl_global_init(CURL_GLOBAL_DEFAULT); curl = curl_easy_init();
if(curl) { // SMTP 设置 curl_easy_setopt(curl, CURLOPT_URL, "smtps://smtp.gmail.com:465"); curl_easy_setopt(curl, CURLOPT_USE_SSL, CURLUSESSL_ALL); curl_easy_setopt(curl, CURLOPT_USERNAME, "your.email@gmail.com"); curl_easy_setopt(curl, CURLOPT_PASSWORD, "app_password");
// 发件人和收件人 curl_easy_setopt(curl, CURLOPT_MAIL_FROM, "<your.email@gmail.com>"); struct curl_slist *recipients = NULL; recipients = curl_slist_append(recipients, "<recipient@example.com>"); curl_easy_setopt(curl, CURLOPT_MAIL_RCPT, recipients);
// 邮件正文 const char *payload_text = "From: Your Name <your.email@gmail.com>\\r" "To: Recipient <recipient@example.com>\\r" "Subject: Test email from C++\\r" "\\r" "Hello! This email was sent using libcurl in C++.\\r";
curl_easy_setopt(curl, CURLOPT_READDATA, payload_text); curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L);
// 执行 res = curl_easy_perform(curl); if(res != CURLE_OK) fprintf(stderr, "Error: %s", curl_easy_strerror(res)); else printf("Email sent!");
curl_slist_free_all(recipients); curl_eas