[ACCEPTED]-sending an email from a C/C++ program in linux-gmail
You could invoke your local MTA directly 1 using popen()
and feed it RFC822-compliant text.
#include <stdio.h>
#include <string.h>
#include <errno.h>
int sendmail(const char *to, const char *from, const char *subject, const char *message)
{
int retval = -1;
FILE *mailpipe = popen("/usr/lib/sendmail -t", "w");
if (mailpipe != NULL) {
fprintf(mailpipe, "To: %s\n", to);
fprintf(mailpipe, "From: %s\n", from);
fprintf(mailpipe, "Subject: %s\n\n", subject);
fwrite(message, 1, strlen(message), mailpipe);
fwrite(".\n", 1, 2, mailpipe);
pclose(mailpipe);
retval = 0;
}
else {
perror("Failed to invoke sendmail");
}
return retval;
}
main(int argc, char** argv)
{
int i;
printf("argc = %d\n", argc);
for (i = 0; i < argc; i++)
printf("argv[%d] = \"%s\"\n", i, argv[i]);
sendmail(argv[1], argv[2], argv[3], argv[4]);
}
libESMTP seems to be what you are looking for. It's 5 very well documented and also seems to be 4 under active development (last Release Candidate 3 is from mid-January 2012). It also supports 2 SSL and various authentication protocols.
There 1 are example applications in the source package.
I like the answer of trojanfoe above, BUT 15 in my case I needed to turn on an email 14 sending agent.. an MTA to enable linux to 13 send emails - I have found exim4 to be 12 a relatively simple MTA to get working and 11 that trojanfoe's program works very nicely 10 with it.
to get it to work I used (on a debian 9 type system in a virtual box (crunchbang 8 linux))
sudo apt-get install exim
sudo apt-get 7 install mailutils
I configured exim4 with
sudo 6 dpkg-reconfigure exim4-config
and I told 5 the computer about my normal (remote) email 4 address with
sudo emacs /etc/email-addresses
hope 3 this might be useful as these were the steps 2 I found worked to get my linux system sending 1 email with trojanfoe's email program above
Do a fork exec and pipe the body to a program 1 like sendmail/mail:
#include <string>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
using std::string;
static const int READEND = 0;
static const int WRITEEND = 1;
int sendEmail(const string& to, const string& subject, const string& body) {
int p2cFd[2];
int ret = pipe(p2cFd);
if (ret) {
return ret;
}
pid_t child_pid = fork();
if (child_pid < 0) {
close(p2cFd[READEND]);
close(p2cFd[WRITEEND]);
return child_pid;
}
else if (!child_pid) {
dup2(p2cFd[READEND], READEND);
close(p2cFd[READEND]);
close(p2cFd[WRITEEND]);
execlp("mail", "mail", "-s", subject.c_str(), to.c_str(), NULL);
exit(EXIT_FAILURE);
}
close(p2cFd[READEND]);
ret = write(p2cFd[WRITEEND], body.c_str(), body.size());
if (ret < 0) {
return ret;
}
close(p2cFd[WRITEEND]);
if (waitpid(child_pid, &ret, 0) == -1) {
return ret;
}
return 0;
}
int main() {
return sendEmail("email@hostname.com", "Subject", "Body");
}
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.