c使用smtp发送邮件
时间: 2023-10-24 21:34:03 浏览: 51
C语言本身没有SMTP协议的支持,但是可以利用第三方库来实现SMTP的功能。常用的SMTP库有libcurl、libesmtp等。
以下是使用libcurl发送邮件的示例代码:
```c
#include <stdio.h>
#include <curl/curl.h>
int main(void)
{
CURL *curl;
CURLcode res = CURLE_OK;
curl = curl_easy_init();
if(curl) {
struct curl_slist *recipients = NULL;
curl_easy_setopt(curl, CURLOPT_URL, "smtp://smtp.example.com");
curl_easy_setopt(curl, CURLOPT_USERNAME, "your_username");
curl_easy_setopt(curl, CURLOPT_PASSWORD, "your_password");
curl_easy_setopt(curl, CURLOPT_MAIL_FROM, "sender@example.com");
recipients = curl_slist_append(recipients, "recipient1@example.com");
recipients = curl_slist_append(recipients, "recipient2@example.com");
curl_easy_setopt(curl, CURLOPT_MAIL_RCPT, recipients);
curl_easy_setopt(curl, CURLOPT_READFUNCTION, NULL);
curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L);
res = curl_easy_perform(curl);
curl_slist_free_all(recipients);
curl_easy_cleanup(curl);
}
return (int)res;
}
```
上述代码使用了libcurl库,需要先安装该库。代码中需要替换相应的SMTP服务器地址、用户名、密码以及发件人和收件人的地址。在实际使用中,还需要添加邮件主题、内容等信息。
需要注意的是,使用SMTP发送邮件需要保证网络连接畅通,同时可能会有一些安全性问题需要考虑。建议在实际使用中仔细评估并采取相应的安全措施。