PHP email Piping get 'to' field - php

I am trying to use email piping with PHP.
I have it working except I can't get the 'To' field.
I am using the following PHP code:
#!/usr/bin/php -q
<?php
// read from stdin
$fd = fopen("php://stdin", "r");
$email = "";
while (!feof($fd))
{
$email .= fread($fd, 1024);
$to1 = explode ("\nTo: ", $email);
$to2 = explode ("\n", $to1[1]);
$to = str_replace ('>', '', str_replace('<', '', $to2[0]));
}
fclose($fd);
mail('email#example.com','From my email pipe!','"' . $to . '"');
?>
If I use a email address (for example: john#smith.com) and send a email to my email address that is forwarded to my PHP piping script (pipe.php) I want it to be able to get who the email was sent to.
For Example:
john#smith.com emails my forwarding email that goes to my PHP piping script (bob#example.com) I want it to return just the bob part only without the #example.com
What happens now is that it returns the whole email address such as "bob#example.com" and I want it to only return bob (without any talking marks).
I have tried using this:
$to = $to.split("#");
but I seem to get an error that says: split() expects at least 2 parameters.
That gets sent to the person who sent the email.
Does anyone know how to do this or know what I might be doing wrong?
This is my first time using Piping in PHP, so if I am doing something wrong please let me know.

Ended up using:
$to1 = explode ("\nTo: ", $email);
$to2 = explode ("\n", $to1[1]);
$to = str_replace ('>', '', str_replace('<', '', $to2[0]));
list($toa, $tob) = explode('#', $to);
then changed the mail to:
mail('email#example.com','From my email pipe!','"' . $toa . '"');

Related

Parse piped email with PHP

I have been trying to setup up a system with this functionality:
Send email to my server
Server pipes email to php script
Php script parses email getting subject and body
Get phone number from subject of email and send text with email body
I have found an email parser here: https://github.com/daniele-occhipinti/php-email-parser
I think I have setup it up correctly but I do not know how to test it besides just sending an email. But I cannot see what my script echos at that point. Also when I do send the email I know something is not working because the text does not send via twilio. What am I doing wrong?
Here is the code:
#!/usr/bin/php -q
<?php
require_once '../resources/Twilio/autoload.php';
use Twilio\Rest\Client;
require('config.php');
// Retrieve Email
require_once("../resources/PlancakeEmailParser.php");
$email = "php://stdin";
$emailParser = new PlancakeEmailParser(file_get_contents($email));
$subject = $emailParser->getSubject();
$text = $emailParser->getPlainBody();
$number = preg_replace('/[^0-9]/', '', $subject);
$phone = "+".$number;
// After this I send the message via Twilio
You are piping the input so you probably need to buffer the stream to ensure you have received all the data before you try and process it.
Something like this:
$dataIn = fopen('php://stdin', 'r');
if ($dataIn) {
$email = '';
while($line = fgets($dataIn)) {
$email .= $line;
}
fclose($dataIn);
}

Save variable as variable in MYSQL for later use

I have an email template which i am saving in database. My problem is some part of message are variable means these data are coming from current user data.
For Example My Template is
$message="This is test for $username. I am sending mail to $email."
here $username and $email is coming from current users and it is varying from user to user.
So problem is how to save it in database so i can use it as variable on php page later.
anybody have any idea please help me.your help would be appreciated.
If you really need to store whole template in database, you can save it using your own created constants e.g. [USERNAME], [EMAIL] and then in php script just use str_replace() on them.
$messageTemplate = 'This is test for [USERNAME]. I am sending mail to [EMAIL].';
$message = str_replace(array('[USERNAME]', '[EMAIL]'), array($username, $email), $messageTemplate);
But you can also divide this string and concatenate it with variables from database as follows:
$message = 'This is test for ' . $username . '. I am sending mail to ' . $email . '.';
You can use something like this:
$input = "This is test for {username}. I am sending mail to {email}.";
$tokens = array("username" => $username, "email" => $email);
$tmp = $input;
foreach($tokens as $key => $token)
{
$tmp = str_replace("{".$key."}", $token, $tmp);
}
echo $tmp;
The variables in the string will not be evaluated as variables automatically just because you are adding it to your php scope. You need to eval the string in order for the variables to be replaced:
$username = 'test';
$email = 'test#test.com';
$str = "This is a test for $username. I am sending mail to some person $email.";
echo $str. "\n";
// This is a test for $username. I am sending mail to some person $email.
eval("\$str = \"$str\";");
echo $str. "\n";
// This is a test for test. I am sending mail to some person test#test.com.
For more information, see http://php.net/manual/en/function.eval.php

php Mail sending double content

I am working on a massmail script which sends an e-mail to every e-mail id present in a particular database.
But there is some issue.
Like I have following database:
id email link
1 a#bc.com bc.com
2 b#cd.com cd.com
And suppose the mail content is : 'Testing this script'
The scripts sends email to a#bc.com perfectly but second time it sends the email, i.e to b#cd.com the content gets doubled.
I mean the second recipient receives an e-mail like this :
Testing this script
Testing this script
The third recipient receives an e-mail with the content repeat three times and the fourth one receives it with four times and so on.
The script grabs e-mail addresses from the email field in the database and sends e-mail to them.
My Code:
<?
include "header.php";
include "config2.php";
$subject="Massmail";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
mysql_connect($server, $db_user, $db_pass)
or die ("Database CONNECT Error");
$resultquery = mysql_db_query($database, "select * from $table");
while ($query = mysql_fetch_array($resultquery))
{
$mailto=$query[$table_email];
$domain=$query[$table_link];
$domain2 = str_replace(array('http://','HTTP://','Http://'), '',$domain);
$handle = fopen("http://$domain2","r") or die("Unable to open link ( $domain ). <a href='javascript:history.go(-1);'>Go back</a> and please try again ");
$contents = '';
while (!feof($handle)) {
$contents .= fread($handle, 8192);
$contents = str_replace('window.location = "/abc.html"','window.location = ""',$contents);
$contents = mb_convert_encoding($contents, "HTML-ENTITIES", "auto");
}
$i = md5(uniqid(rand(), true)) . '.' . html;
$fh = fopen("/home/host/public_html/content/$i", "w");
fwrite($fh, $contents);
fclose($fh);
$filename = '/files/$i';
$message1 .= "Testing Mail Script Version 2";
mail($mailto, $subject, $message1, $headers, "-f" . 'noreply#domain.com');
echo 'Mail sent to '.$mailto.'<br>';
sleep($seconds);
}
include "footer.php";
?>
I have tried to echo the mail that has to be sent and I get this:
To: a#bc.com
Subject: Massmail
Message:
Testing mail script
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
to: b#cd.com
Subject: Massmail
Message:
Testing mail scriptTesting mail script
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Your help will be greatly appreciated. Thanks in advance
In the code line: $message1 .= "Testing Mail Script Version 2"; the period is a concatenate, so each time you loop it, you duplicate the message another time.
Agreed. Sounds like your loop is not functioning correctly? If you can't post the full code, try to post an abstraction for us to diagnose your issue.
If you cant, I would look into looping based on the number of email address you have, not some arbitrary counter. That might help you out.
Suppose this is your table. With id, email, link, message structured as:
id email message
1 a#test.com hello, how are you doing..
2 b#test.com hey, dude this is me..
3 c#test.com we are sending you this...
Now, let's assume you have 100 records. What I would do is (assuming $result is a mysql array returning all the results from mysql ex SELECT * FROM mail...)
I would try:
for($i=0; $i <= count($result); $i++){
$send = mail($result['to'], $result['subject'],
$result['message'], $result['headers']);
if(!$send){
echo 'e-mail, sending has stopped';
break;
}
else{
echo 'all e-mails are sent successfully'; }
}
Never mind, I fixed it. #Pirion's post helped me. I changed
$message1 .= "Testing Mail Script Version 2";
to
$message = "Testing Mail Script Version 2";
And everything worked perfectly. Thank You So Much Guys For Helping Me Out.

Email piping with php script to collect the TO field?

I want to forward my bounced emails to a php script to deal with them. I am using.
#!/usr/bin/php -q
<?php
// read from stdin
$fd = fopen("php://stdin", "r");
$email = "";
while (!feof($fd)) {
$email .= fread($fd, 1024);
}
fclose($fd);
// 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];
}
} else {
// not a header, but message
$message .= $lines[$i]."\n";
}
if (trim($lines[$i])=="") {
// empty line, header section has ended
$splittingheaders = false;
}
}
?>
Works perfect! But how do I collect the "To" field in the bounced message? I've tried just adding a $to variable but it doesn't work.
Any help would be great,
thanks,
EDIT: Actually I need to get the "TO" field within the body of the message. - The email that it bounced back from. How do I pull apart the body of the message to take specific info? Should I create a special header with the person's email so that it is easier to get this info?
If you can create a custom header, that would be easiest. Otherwise, you need to match against your entire body for a particular pattern; and if your body text can vary, it could be difficult to make sure you are always matching the correct text.
Custom headers should begin with X-, so maybe do something like:
if (preg_match("/^X-Originally-To: (.*)/", $lines[$i], $matches)) {
$originallyto = $matches[1];
}
But with X- headers, they are non-standard, so it is best to pick a name that is either
Commonly used exclusively for the same purpose, or
Not likely to be used by anyone else at all
One other thing you should be aware of; lines in a message should always end in "\r\n", so you might want to split on both characters (instead of just "\n") to ensure more consistent behaviour.

send email to multiple recepients

I'm trying to send an e-mail to multiple e-mail address in my database. Here is my current code. It is only working when I specify a single e-mail address, however, I need to have them query my database and send the e-mail to each e-mail address. Where am I going wrong here?
$elist = $database->getRows("SELECT * FROM `emails`");
if ($elist) {
foreach ($elist as $elist_result) {
$frm = 'rdsyh#gmail.com';
$sub = 'Weekly Work Report';
ob_start(); // start output buffering
include_once('mail_content.php');
$mail_body = ob_get_contents(); // get the contents from the buffer
ob_end_clean();
$to = $elist_result['email'];
$mailstatus = l_mail('', '', $to, $elist_result['firstname'] . ' ' . $elist_result['lastname'], $frm, 'HR', $sub, $mail_body);
}
}
if ($mailstatus == 'ok') {
echo '<center><font color=red style="font-size:14px">Message has been sent Succesfully.....!</font></center><br>';
} else {
echo $mailstatus;
}
Well, there's a lot of abstraction here that we know nothing about from your code. Things to check:
Are you certain that your database query is returning all of the results you're looking for (is $elist populated properly)?
Are you certain that the query is returning data in the format that you're trying to access it in (is $to populated properly)?
Are you certain your l_mail() function is behaving (is it possible it exit's or otherwise terminates script execution in the middle of the first pass)?
Based on what I see here, if everything else was working properly, you should successfully be sending a bunch of emails, one to each email in your list.
Now, if instead you're trying to send a single email that is sent to all of the addresses at once, then you need to group the email addresses in the for loop and then run your mail function afterwards:
<?
$tos = array();
foreach ($elist as $elist_result) {
$tos[] = $elist_result['email'];
}
$frm = 'rdsyh#gmail.com';
$sub = 'Weekly Work Report';
ob_start(); // start output buffering
include_once('mail_content.php');
$mail_body = ob_get_contents(); // get the contents from the buffer
ob_end_clean();
$to = implode(', ', $tos);
$mailstatus = l_mail('', '', $to, $elist_result['firstname'] . ' ' . $elist_result['lastname'], $frm, 'HR', $sub, $mail_body);
?>
What does l_mail() do? If its a web service, then it might have limit for mass emails.

Categories