0

What I am trying to do, is have my c program execute a function that uses the system() function with mailx. When I output the variable that holds the const *char that the system() function needs it looks fine. But I do not get the email. Yet when I run the mailx command via CLI, I get the email. Here is my code: Thank you in advance

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void send_email(char *to_who, char *subject, char *message)
{
    char command[1024];
    char command_buffer[1024];  

    if (snprintf(command_buffer, sizeof(command_buffer), "echo \"%s\" | mailx -s \"%s\" %s", message, subject, to_who) >= sizeof(command_buffer))
    {
        printf("Command Buffer Overload");
    }

    strcpy(command, command_buffer);
    system(command);

    //Check to see command contents
    printf("%s", command);  
}

int main ()
{

 send_email("user@email.com","C Email Test", "Test Email with C");

return 0;
}
Vlad
  • 145
  • 6
  • 19
  • Have a look at this: HTH – jaaq Jun 30 '16 at 00:20
  • 1
    For starters would suggest you check the return value of `system` to get the command return status and what the precise error code is if it failed. (Aside: it's a bit pointless to `strcpy` into a new buffer. Just use the result of the `snprintf` directly). – kaylum Jun 30 '16 at 00:26
  • @kaylum how do I return the value of the system function? – Vlad Jun 30 '16 at 00:27
  • Not sure what you mean. `int rval = system(..);`. Then have conditional checks on `rval` and print out that value for debugging. – kaylum Jun 30 '16 at 00:29
  • @kaylum the value returned is 0 – Vlad Jun 30 '16 at 00:35
  • @jaaq I took a look at the thread and I tried a few of things, but still no luck – Vlad Jun 30 '16 at 00:54
  • I tried your program and it worked fine. – Barmar Jun 30 '16 at 01:29
  • @Barmar thank you, in that case it must be somethin wrong with my Pi, would you happen to have an idea of what it might be? – Vlad Jun 30 '16 at 01:37
  • I can't think of a reason why it would work from the CLI but not from C on the same machine. Are you running the program from a different account? Maybe the `mailx` command isn't in its `$PATH`. Try using the full path to the command. – Barmar Jun 30 '16 at 01:40
  • @Barmar I tried to run the program with the full path /usr/bin/mailx and still same issue. Works on terminal but not in the C. This is really odd – Vlad Jun 30 '16 at 18:31
  • Does the `system()` function work with other commands, e.g. `system("echo foo");`? – Barmar Jun 30 '16 at 18:57

0 Answers0