Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

EMail from c++ 1

Status
Not open for further replies.

mfreeze

Programmer
Sep 11, 2003
16
0
0
US
Could someone give an example of how to 'hand-off' an email to sendmail from c++?

My situation is that I'm trying to send a variable list of items to a predefined set of recipients through a c++ program.

Thanks,
Mark.
 
Crudely, you can do something like this.
Code:
void sendEmail ( char *to, char *subject ) {
  char cmd[1000];
  sprintf( cmd, "mail -s %s %s", subject, to );
  system( cmd );
}

But you'd need to read the manual page on your local 'mail' program to be sure of the syntax for sending email from the command line.

--
 
Code:
void sendEmail ( char *to, char *subject ) {
  char cmd[1000];
  sprintf( cmd, "mail -s %s %s", subject, to );
  system( cmd );
}

Isn't bad, but I prefer:
Code:
#include <unistd.h>
#include <wait.h>
#include <string>
using namespace std;

int mail(char* to, char* subject)
{
  const char* mail = "mail";
  
  char* args[4] = {"mail","-s",to,subject};
  int pid;
  int status;

  if((pid = fork()) = 0)
  {
     execvp(mail,args);
  }
  else
  {
     waitpid(pid,&status,0);
  }  
  return status;
}

int main()
{
	int x = mail("some_user@example.com","test page");
	return x;
}

The change in the two is "system()" evokes an extra C shell, exec doesn't, but it means you have to do the forking yourself. The other difference is that you have more information back -- the return error code and erno from the forking and executing. Granted system gives you return code, but you threw it away.

Just my take on it.

NOTE: This only works on POSIX (and most POSIX like) systems with the mail command. unistd.h is C++ standard, but POSIX -- but if you've got mail, you likely (almost certianly) have unistd.h

[plug=shameless]
[/plug]
 
> char* args[4] = {"mail","-s",to,subject};
You forgot the NULL
[tt]char* args[5] = {"mail","-s",to,subject,NULL};[/tt]

Also, you can save a variable, and possible confusion by doing
[tt]execvp(args[0],args);[/tt]

--
 
Star for salem... I tried using strings, but had a problem with c_str() and the constness of the char pointers... So, I decided to use the char pointers and it was in that change that the extra variable came from.

The missing null was an oversight that I should have caught. When I tested it, it ran without a problem; but I know your right about the NULL... I'm supprised it did work on my test run.

Star for you.

[plug=shameless]
[/plug]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top