/** * \brief Function to send an email to a user * \param user the user to whom send the email * \param content the body of the email * \param subject the subject of the email * \param sendmailScriptPath The path to the script for sending emails */ int UserServer::sendMailToUser(const UMS_Data::User& user, std::string content, std::string subject, std::string sendmailScriptPath) { std::vector<std::string> tokens; std::ostringstream command; pid_t pid; std::string address = user.getEmail(); //If the address is empty if (address.empty()) { throw UserException(ERRCODE_INVALID_MAIL_ADRESS, "Empty email address"); } //If the script is empty if (sendmailScriptPath.empty()) { throw SystemException(ERRCODE_SYSTEM, "Invalid server configuration"); } // To build the script command command << sendmailScriptPath << " --to " << address << " -s "; std::istringstream is(command.str()); std::copy(std::istream_iterator<std::string>(is), std::istream_iterator<std::string>(), std::back_inserter<std::vector<std::string> >(tokens)); char* argv[tokens.size()+6]; argv[tokens.size()+5]=NULL; //Use of tokens for (unsigned int i = 0; i < tokens.size(); ++i) { argv[i]=strdup(tokens[i].c_str()); } //To avoid mutiple values by using tokens because of spaces argv[tokens.size()]=strdup(subject.c_str()); argv[tokens.size()+1]=strdup(content.c_str()); //To execute the script on background argv[tokens.size()+2]=strdup(" 1>/dev/null "); argv[tokens.size()+3]=strdup(" 2>/dev/null "); argv[tokens.size()+4]=strdup(" & "); pid = fork(); if (pid == -1) {//if an error occurs during fork for (unsigned int i=0; i<tokens.size()+5; ++i) { free(argv[i]); } throw SystemException(ERRCODE_SYSTEM, "Error during the creation of the process for sending mail to " +user.getFirstname()+ " with userId:" +user.getUserId()); } if (pid == 0) {//if the child process freopen("dev/null", "r", stdin); freopen("dev/null", "w", stdout); freopen("dev/null", "w", stderr); if (execv(argv[0], argv) == -1) { for (unsigned int i=0; i<tokens.size()+5; ++i) { free(argv[i]); } exit(1); } } for (unsigned int i=0; i<tokens.size()+5; ++i) { free(argv[i]); } return 0; }