Email Piping with PHP Script using cpanel - php

I am trying to email piping with cpanel and PHP script. Its working fine. I am looking for get From Address, Subject and Message from received email. My script is like below
#!/usr/bin/php -q
<?php
/*$fd = fopen( "php://stdin", "r" );
$message = "";
while ( !feof( $fd ) )
{
$message .= fread( $fd, 1024 );
}
fclose( $fd );*/
$fd = fopen("php://stdin", "r");
$message = "";
while (!feof($fd)) {
$message .= fread($fd, 1024);
}
fclose($fd);
//split the string into array of strings, each of the string represents a single line, received
$lines = explode("\n", $message);
// initialize variable which will assigned later on
$from = "";
$subject = "";
$headers = "";
$message = "";
$is_header= true;
//loop through each line
for ($i=0; $i < count($lines); $i++) {
if ($is_header) {
// hear information. instead of main message body, all other information are here.
$headers .= $lines[$i]."\n";
// Split out the subject portion
if (preg_match("/^Subject: (.*)/", $lines[$i], $matches)) {
$subject = $matches[1];
}
//Split out the sender information portion
if (preg_match("/^From: (.*)/", $lines[$i], $matches)) {
$from = $matches[1];
}
} else {
// content/main message body information
$message .= $lines[$i]."\n";
}
if (trim($lines[$i])=="") {
// empty line, header section has ended
$is_header = false;
}
}
$to = 'myemail#gmail.com';
$subject = 'the subject';
$message1 = "You have new message from :".$from. "and message is" .$message;
$headers = 'From: webmaster#mydomain.com' . "\r\n" .
'Reply-To: webmaster#mydomain.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $message1, $headers);
?>
I am getting result in my email like below
You have new message from :FirstName LastName <senderemail#gmail.com>and message is--00000000000045a1e5059ef97af8
Content-Type: text/plain; charset="UTF-8"
This is Body text Message
--00000000000045a1e5059ef97af8
Content-Type: text/html; charset="UTF-8"
<div dir="ltr"><div class="gmail_default" style="font-family:georgia,serif;font-size:large">This is text<br></div></div>
--00000000000045a1e5059ef97af8--
However its contain unnecessary words in it. I want plain output like below
You have new message from :senderemail#gmail.com and message is This is Body text Message
Sorry I am new in PHP and does not able to solve the issue. Let me know if anyone can help me for extract and get output like this.
Thanks!

Related

PHP pipe to script email

I am trying to forward all emails from support#example.com to PHP script to be inserted into MySql.
My script works, but I have two issues.
The from email address shows the name of the sender, not the email address.
The email body content shows for eg.
--00000000000095430105a9347fe3
Content-Type: text/plain; charset="UTF-8"
This is a test email
--00000000000095430105a9347fe3
Content-Type: text/html; charset="UTF-8"
This is a test email
--00000000000095430105a9347fe3--
Instead of just the body of the email This is a test email
This is my code:
// handle email
$lines = explode("\n", $email);
// empty vars
$from = "";
$subject = "";
$headers = "";
$message = "";
$splittingheaders = true;
for ($i=0; $i < count($lines); $i++) {
if ($splittingheaders) {
// this is a header
$headers .= $lines[$i]."\n";
// look out for special headers
if (preg_match("/^Subject: (.*)/", $lines[$i], $matches)) {
$subject = $matches[1];
}
if (preg_match("/^From: (.*)/", $lines[$i], $matches)) {
$from = $matches[1];
}
if (preg_match("/^To: (.*)/", $lines[$i], $matches)) {
$to = $matches[1];
}
} else {
// content/main message body information
$message .= $lines[$i]."\n";
}
if (trim($lines[$i])=="") {
// empty line, header section has ended
$splittingheaders = false;
}
}
I have tried
$message = imap_fetchbody($mbox,1,'1');
$message = strip_tags(quoted_printable_decode(imap_fetchbody($mbox,1,"1")));
$message = strip_tags($message, '<body>');
$message = explode(">", $message);
$message = explode("<", $message[1]);
$message = str_replace(" ", "", $message[0]);
$message = html_entity_decode($message);
$message = trim($message);
And I tried this but could not figure out how to make it work:
$emailnumberPattern = "--[0]{12}";
$replacement = " ";
preg_replace($emailnumberPattern, $replacement, $string);
$message .= $lines[$i]."\n";
Any help would be welcome to show the sender email as well as remove unwanted content from the email body.
Parsing emails is no easy task that can be solved with a couple of regexes. You should definitely use a dedicated extension or program. Also, you shold avoid loading the entire message into a single string (or array).
This one is just a single composer command away: composer require zbateson/mail-mime-parser.
require __DIR__ . '/vendor/autoload.php';
$handle = fopen('php://stdin', 'r');
$message = \ZBateson\MailMimeParser\Message::from($handle);
fclose($handle);
$from = $message->getHeaderValue('from');
$body = $message->getTextContent();
That said, you can obtain some results with your code, which I've modified as little as possible:
$lines = explode("\n", $email);
// empty vars
$from = "";
$subject = "";
$headers = "";
$message = "";
$splittingheaders = true;
for ($i=0; $i < count($lines); $i++) {
if ($splittingheaders) {
// this is a header
$headers .= $lines[$i]."\n";
// look out for special headers
if (preg_match("/^Subject: (.*)/", $lines[$i], $matches)) {
$subject = $matches[1];
}
if (preg_match("/^From: (.*)/", $lines[$i], $matches)) {
$from = $matches[1];
}
if (preg_match("/^To: (.*)/", $lines[$i], $matches)) {
$to = $matches[1];
}
} else {
if (preg_match('/Content-Type: text\/plain; charset=/', $lines[$i])) {
$m = true;
continue;
}
if (preg_match('/Content-Type:/', $lines[$i])) {
$m = false;
}
if ($m) {
$message .= $lines[$i]."\n";
}
}
if (trim($lines[$i])=="") {
// empty line, header section has ended
$splittingheaders = false;
}
}
if (preg_match('/ <(.*)>/', $from, $matches)){
$from = $matches[1];
}
Those results are not guaranteed, and highly dependent on the input format. For a robust solution, please use a well-tested parser.

Parsing Email with >Forward on cPanel

I'm trying to use this E-mail parser on my VPS with cPanel.
I have forwarded incoming emails to my script but I get an error emailed back at me:
This message was created automatically by mail delivery software.
A message that you sent could not be delivered to one or more of its
recipients. This is a permanent error. The following address(es) failed:
pipe to |/home/../parser_3.php
generated by domain.tld
local delivery failed
The following text was generated during the delivery attempt:
------ pipe to |/home/../parser_3.php
generated by test3#domain.tld ------
Could not exec '/home/../parser_3.php'
Reporting-MTA: dos; domain.tld
Action: failed
Final-Recipient: rfc822;|/home/../parser_3.php
Status: 5.0.0
Since I have used the script as it is, I am thinking maybe I need to install some php package to get it to work?
chdir(dirname(__FILE__));
$fd = fopen("php://stdin", "r");
$email = "";
while (!feof($fd)) {
$email .= fread($fd, 1024);
}
fclose($fd);
if(strlen($email)<1) {
die();
}
// handle email
$lines = explode("\n", $email);
// empty vars
$from = "";
$to="";
$subject = "";
$headers = "";
$message = "";
$splittingheaders = true;
for ($i=0; $i < count($lines); $i++) {
if ($splittingheaders) {
// this is a header
$headers .= $lines[$i]."\n";
// look out for special headers
if (preg_match("/^Subject: (.*)/", $lines[$i], $matches)) {
$subject = $matches[1];
}
if (preg_match("/^From: (.*)/", $lines[$i], $matches)) {
$from = $matches[1];
}
if (preg_match("/^To: (.*)/", $lines[$i], $matches)) {
$to = $matches[1];
}
} else {
// not a header, but message
$message .= $lines[$i]."\n";
}
if (trim($lines[$i])=="") {
// empty line, header section has ended
$splittingheaders = false;
}
}
$to = $unprocessed_email;
$subject = 'TEST PARSER 3 - '.$date = date('md his', time()).'';
$message = '<br><br> From: '. $from .' <br><br> To: '. $to .' <br><br> Subject: '. $subject .' <br><br> Headers: '. $headers .' <br><br> Message: '. $message .' <br><br><br>'. print_r( $email, true ) .'';
$headers = 'From: "Email-Parser" <parser#domain.tld>' . "\r\n" .
'MIME-Version: 1.0' . "\r\n" .
'Content-type: text/html; charset=UTF-8' . "\r\n".
'X-Mailer: PHPv: '.phpversion() . "\r\n" .
'';
$result = mail($to, $subject, $message, $headers);
if ($result) echo 'Mail accepted for delivery ';
if (!$result) echo 'Test unsuccessful... '
Or maybe it doesn't work at all on PHP 7?
The outcome would be to parse incoming emails. And shoot them over to my email. And later on add the to a database, assuming I get the parsing working.

Send php mail using emails.txt and custom message from message.txt

I'm trying to send email using PHP
I have emails.txt with a list of emails and names split by ';'
and I also have content.txt with the email message, for example, "Hello Mr. $name"
I want to send an email, for all users, using content.txt file and alter the $name using the emails.txt to replace the string $name
I built some parts, but I'm stuck
<?php
$file = fopen("emails.txt", "r");
$filecontent = fopen("content.txt", "r");
while(!feof($file)){
$line = fgets($file);
$to = $line;
$subject = "This is subject";
$message = "<b>This is HTML message.</b>";
$message .= "<h1>This is headline.</h1>";
$header = "From:abc#somedomain.com \r\n";
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-type: text/html\r\n";
$retval = mail ($to,$subject,$message,$header);
if( $retval == true ) {
echo "Message sent successfully...";
}else {
echo "Message could not be sent...";
}
}
fclose($file);
?>
another part
<?php
$path_to_file = 'content.txt';
$file_contents = file_get_contents($path_to_file);
$file_contents = str_replace("$name","$correctname",$file_contents);
file_put_contents($path_to_file,$file_contents);
?>

Email Piping - Read Attachment (.txt file)

I'm using email piping to save data sent by an end user through email; however, one requirement is that the user sends a text file with additional information.
Therefore, I need the email piping script to get the attachment, and read it. It's a simple text (.txt) document, base64 encoding, example:
Content-Type: text/plain; charset=UTF-8
Content-ID: <text_doc>
Content-Location: text_doc.txt
Content-Transfer-Encoding: BASE64
This is my Email Piping script. The email passes through fine, I just need to get the attachment.
<?php
chdir(dirname(__FILE__));
$fd = fopen("php://stdin", "r");
$email = "";
while (!feof($fd)) {
$email .= fread($fd, 1024);
}
fclose($fd);
if(strlen($email)<1) {
die();
}
// handle email
$lines = explode("\n", $email);
// empty vars
$from = "";
$to="";
$subject = "";
$headers = "";
$message = "";
$splittingheaders = true;
for ($i=0; $i < count($lines); $i++) {
if ($splittingheaders) {
// this is a header
$headers .= $lines[$i]."\n";
// look out for special headers
if (preg_match("/^Subject: (.*)/", $lines[$i], $matches)) {
$subject = $matches[1];
}
if (preg_match("/^From: (.*)/", $lines[$i], $matches)) {
$from = $matches[1];
}
if (preg_match("/^To: (.*)/", $lines[$i], $matches)) {
$to = $matches[1];
}
} else {
// not a header, but message
$message .= $lines[$i]."\n";
}
if (trim($lines[$i])=="") {
// empty line, header section has ended
$splittingheaders = false;
}
}

PHP Order Form - Email with Attachment

I am trying to create an order form which when complete, passes you on to the order.php page (sends the email), where you are then passed on to paypal. Everything was working fine until i tried to add attachments, when i added the code for attachment, the email is no longer sent.
<?php
$to = 'hidden' ;
$from = $_REQUEST['email'] ;
$name = $_REQUEST['name'] ;
$headers = "From: $from";
$subject = "Distinctive Writers - Contact Form";
$tprice = $_REQUEST['tprice'] ;
$fields = array();
$fields{"name"} = "name";
$fields{"email"} = "email";
$fields{"number"} = "number";
$fields{"subject"} = "subject";
$fields{"doctype"} = "doctype";
$fields{"spec"} = "spec";
$fields{"grade"} = "grade";
$fields{"days"} = "days";
$fields{"due"} = "due";
$fields{"pages"} = "pages";
$fields{"price"} = "price";
$mime_boundary="==Multipart_Boundary_x".md5(mt_rand())."x";
$tmp_name = $_FILES['filename']['tmp_name'];
$type = $_FILES['filename']['type'];
$file_name = $_FILES['filename']['name'];
$size = $_FILES['filename']['size'];
if (file_exists($tmp_name)){
// Check to make sure that it is an uploaded file and not a system file
if(is_uploaded_file($tmp_name)){
// Now Open the file for a binary read
$file = fopen($tmp_name,'rb');
// Now read the file content into a variable
$data = fread($file,filesize($tmp_name));
// close the file
fclose($file);
// Now we need to encode it and split it into acceptable length lines
$data = chunk_split(base64_encode($data));
}
// Now we'll build the message headers
$headers = "From: $from\r\n" .
"MIME-Version: 1.0\r\n" .
"Content-Type: multipart/mixed;\r\n" .
" boundary=\"{$mime_boundary}\"";
// Now we'll insert a boundary to indicate we're starting the attachment we have to specify the content type, file name, and disposition as an attachment, then add the file content and set another boundary to indicate that the end of the file has been reached
$message .= "--{$mime_boundary}\n" .
"Content-Type: {$type};\n" .
" name=\"{$file_name}\"\n" .
//"Content-Disposition: attachment;\n" .
//" filename=\"{$fileatt_name}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data . "\n\n" .
"--{$mime_boundary}--\n";
$body = "We have received the following information:\n\n"; foreach($fields as $a => $b){ $body .= sprintf("%20s: %s\n",$b,$_REQUEST[$a]); }
$headers2 = "From: noreply#YourCompany.com";
$subject2 = "Thank you for contacting us";
$autoreply = "Thank you for contacting us. Somebody will get back to you as soon as possible, usualy within 48 hours. If you have any more questions, please consult our website at www.oursite.com";
if($from == '') {print "You have not entered an email, please go back and try again";}
else {
if($name == '') {print "You have not entered a name, please go back and try again";}
else {
$send = mail($to, $subject, $body, $headers, $message);
$send2 = mail($from, $subject2, $autoreply, $headers2);
}
}
if(!mail($to, $subject, $body, $headers, $message)){
print "ERROR!!";
}
}
?>
I recommend PHPMailer too as mentioned by pc-shooter
then you can use
$mail = new PHPMailer();
then you can utilize either one of these two
$mail->AddStringAttachment($string,$filename)
$mail->AddAttachment($path);
Something to keep in mind, something else might be blocking the email. if the mail function returns TRUE then the mail was dispatched.

Categories