C to mails send using gmail
You want to send emails using Gmail from a C program. Here's a simple example of how you can do it using the libcurl
library, which is a popular C library for transferring data over HTTP.
First, you need to install libcurl
on your system. The installation process varies depending on your operating system. For example, on Ubuntu, you can install it using the following command:
sudo apt-get install libcurl4-openssl-dev
Once you have libcurl
installed, you can use the following C program to send an email using Gmail:
#include <stdio.h>
#include <curl/curl.h>
int main() {
CURL *curl;
CURLcode res;
// Set up the email details
const char *username = "[email protected]";
const char *password = "your_password";
const char *to = "[email protected]";
const char *subject = "Test email from C program";
const char *body = "This is a test email sent from a C program using Gmail.";
// Set up the curl session
curl_global_init(CURL_GLOBAL_DEFAULT);
curl = curl_easy_init();
if(curl) {
// Set the URL for the email
curl_easy_setopt(curl, CURLOPT_URL, "smtp://smtp.gmail.com:587");
// Set the username and password
curl_easy_setopt(curl, CURLOPT_USERNAME, username);
curl_easy_setopt(curl, CURLOPT_PASSWORD, password);
// Set the from and to addresses
curl_easy_setopt(curl, CURLOPT_MAIL_FROM, "<" username ">");
curl_easy_setopt(curl, CURLOPT_MAIL_RCPT, "<" to ">");
// Set the subject and body of the email
curl_easy_setopt(curl, CURLOPT_READDATA, body);
curl_easy_setopt(curl, CURLOPT_READFUNCTION, NULL);
// Set the subject of the email
curl_easy_setopt(curl, CURLOPT_READHEADER, subject);
// Send the email
res = curl_easy_perform(curl);
// Check for errors
if(res!= CURLE_OK) {
fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
}
// Clean up
curl_easy_cleanup(curl);
}
curl_global_cleanup();
return 0;
}
This program uses the curl
library to send an email using the SMTP protocol. It sets up the email details, such as the from and to addresses, subject, and body, and then sends the email using the curl_easy_perform
function.
Note that you need to replace [email protected]
and your_password
with your actual Gmail username and password. Also, make sure to enable "Less secure app access" in your Google Account settings to allow this program to send emails using your Gmail account.
To compile this program, you can use the following command:
gcc -o send_email send_email.c -lcurl
This will create an executable file called send_email
that you can run to send an email using Gmail.