E-mail piping with e-mail forwarder does not work - php

I have a simple email pipe script. But I need a copy of the incoming e-mail going to another e-mail address. Unfortunately I do not receive the e-mail as I wanted.
The code;
#!/usr/bin/php -q
<?php
$email_msg = ''; // the content of the email that is being piped
$email_addr = 'sales#flensmuts.nl'; // where the email will be sent
$subject = 'Piped:'; // the subject of the email being sent
// open a handle to the email
$fh = fopen("php://stdin", "r");
// read through the email until the end
while (!feof($fh)){
$email_msg .= fread($fh, 1024);
}
fclose($fh);
// send a copy of the email to your account
mail($email_addr, $subject, "Piped Email: ".$email_msg);
?>

Your mail server logs will probably say something about this. My guess is that it might be failing because your message is malformed because of the prefix you're adding. Try sending the message untouched, like this:
mail($email_addr, $subject, $email_msg);
Separately, for simple forwarding like this, you can probably set up your mail server to do this directly without having to go via a script.

There is no error checking in your script. There is no instrumentation in your script to see if it is even being run. You have not said why you believe that the script is being triggered. You have not said how mail() works on your test site.
Decompose the issues. Replace this script with one which dumps stein to a file to find out if there is an issue with the input integration.
Write and run a script which sends an email when using mail() when manually invoked. If you control the MTA then read your logs - even if these experiments are successful.
Then go back to your original script. Add some logging. Check the value returned by mail(). Check that the delivery path accepts forwarded mail with a broken envelope.

Related

Modifying & Relaying Mail

Is there any way to simply relay mails received by a PHP script? Instead of being received normally into a mailbox, I have routed all incoming mails to a PHP script that would parse and log them (from, subject, message text) into a text file.
This is the truncated version of the script:.
<?php
$feed = fopen ("php://stdin", 'r');
$email = '';
while (!feof($feed))
{
$email .= fread($feed, 1024);
}
fclose($feed);
$to = explode...
$from = explode..
$subject = explode...
$message = utf8_encode...
$log = fopen("/home/.../log.txt", "a+");
fwrite($log,...);
fclose($log);
?>
Would it be possible to relay the entire message, as is, to another recipient, but not as a forward?
TIA.
Apparently, the email is received with a whole bunch of additional headers, from the original sender. So, it must be parsed, and only the required headers extracted and used. The relevant header entries could also be modified to change the sender & recipient information, as well as the subject. Once all that is done, the PHP mail() function could be used to re-send the email.
Simple, and it works. The only drawback is that GMail keeps reporting that the sender cannot be confirmed as the actual sender (or spammer).

500 error after PHP mail()

UPDATE
I was able to get the hosting info from my client and I contacted support, apparently there's an issue with the hosts mail function at the moment and they are working on a resolution. Will wait to see if that's the cause of this problem and will report back.
END UPDATE
I am trying to set up a simple contact form that will send an email. I have the form action set to the below PHP file.
The email gets sent, but the user experience ends with a 500 error instead of sending the user to the confirmation page.
If I comment out the mail() part, then the form redirects the user to the confirmation page successfully, but of course no email gets sent.
The website is hosted on GoDaddy, and I don't have access to the hosting account, though I can try to get it if I need it.
Here's the PHP code:
<?php
$name = $_POST['name'];
$address = $_POST['address'];
$city = $_POST['CITY'];
$state = $_POST['state'];
$zip = $_POST['zip'];
$email = $_POST['email'];
$howdidyouhear = $_POST['hear_about'];
$notifyshow = $_POST['notify_shows'];
$notifyonline = $_POST['notify_online'];
$interest_jewelry = $_POST['Interest_jewelry'];
$interest_prints = $_POST['interest_prints'];
$interest_folkart = $_POST['interest_folkart'];
$interest_indian = $_POST['interest_indian'];
$interest_closeouts = $_POST['interest_closeouts'];
$interest_other = $_POST['interest_other'];
$interest_other_text = $_POST['interest_other_text'];
$spamvalid = $_POST['validate'];
$honeypot = $_POST['website'];
//Spammer Handling
if ($honeypot!=null){echo 'You have been flagged as a spammer, please go away!'; exit;}
if ($spamvalid != '357'){
echo "
<script>
function goBack() {
window.history.back()
}
</script>
You didn't enter the correct number at the bottom of the form. Please try again.<br><button onclick='goBack()'>Go Back</button>";
exit;
}
//START EMAIL
//Body
$mailbody="Name: {$name}\n\nAddress: {$address}\n\nCity: {$city}\n\nState: {$state}\n\nZip: {$zip}\n\nEmail: {$email}\n\nHow did you hear about us?: {$howdidyouhear}\n\nWould you like to be notified when we will be doing a show in your area?: {$notifyshow}\n\nWould you like to receive email notifications of special sales and online events?: {$notifyonline}\n\nWhat brought you to mishuganah.com?: {$interest_jewelry} {$interest_prints} {$interest_folkart} {$interest_indian} {$interest_closeouts} {$interest_other}: {$interest_other_text}\n\n";
//Send Email
mail('matt.rodela#gmail.com','New submission from Mishuganah.com', $mailbody, "From:{$email}\r\n" );
header("Location: http://".$_SERVER["HTTP_HOST"]."/mailing_list/confirmation_page.htm");
?>
I am a relative novice with PHP, so please explain your solutions fully. Thanks!
Use phpMailer instead of php mail() function below you will find reasons not to use built in php mail function
In some cases, mails send via PHP mail() did not receive the recipients although it was send by WB without any error message. The most common reasons for that issue are listed below.
wrong format of mail header or content (e.g. differences in line break between Windows/Unix)
sendmail not installed or configured on your server (php.ini)
the mail provider of the recipeint does not allow mails send by PHP mail(); common spam protection
Errors in the format of header or content can cause that mails are treated as SPAM. In the best case, such mails are transfered to the spam folder of your recipient inbox or send back to the sender. In the worst case, such mails are deleted without any comment. If sendmail is not installed or not configured, no mails can be send at all.
It is common practice by free mail provider such as GMX, to reject mails send via the PHP function mail(). Very often such mails are deleted without any information of the recipient.
So it turns out it was an issue on GoDaddy's end and it has been resolved. The form is working now. Apparently there was nothing wrong with the code.
Thanks for the suggestions folks, I learned some stuff (going to sanatize and filter my inputs now).

HTML form PHP post to email

I'd like to make a form that posts data to my email.
I found the following code and it works fine except I didn't get any email from the form.
Here is the Php File
<?php
// Contact subject
$name ="$name";
// Details
$address="$address";
$id="$id";
$passport="$passport";
$issue="$issue";
$mula="$mula";
$tamat="$tamat";
$tel="$tel";
$select_dd="$select_dd";
$date="$date";
$textarea="$textarea";
$file="$file";
// Mail of sender
$email="$email";
// From
$header="from: $name <$mail>";
// Enter your email address
$to ='rodhiahazzahra#gmail.com';
$send_contact=mail($to,$subject,$message,$header);
// Check, if message sent to your email
// display message "We've recived your information"
if($send_contact){
echo "We've recived your contact information";
}
else {
echo "ERROR";
}?>
Where did you try this code? Local or on a Server? Is there sendmail (or similar) installed and properly configured on your server?
Quote from PHP - Mail Function
It is important to note that just because the mail was accepted for delivery, it does NOT mean the mail will actually reach the intended destination.
You should check your configuration on the server and check the mail logs and you spam-folder.
If i am not mistaken, you need to set the SMTP server before you call mail().
ini_set('SMTP','mySMTP.serv');
Cheers
Edit:
Caution
(Windows only) When PHP is talking to a SMTP server directly, if a full stop is found
on the start of a line, it is removed. To counter-act this, replace these occurrences
with a double dot.
<?php
$text = str_replace("\n.", "\n..", $text);
?>
If you just started learning, one of the basic rules is always RTM before you start using a function. here is the link for PHP Mail function http://us3.php.net/manual/en/function.mail.php

email application help. Send email to made up email address which is redirected to real email

I'm wondering how i would go about making the following application:
a user signs up, say with the username "johny-jones".
Lets say for example that my domain is www.example.com
if anyone emails johny-jones#example.com this email is redirected to johny-jones REAL email address
The simplest option is to tell your smtp server to forward all ingoing mails to an external program (your php script). For example, for qmail this will be like | php myphpscript.php in .qmail file. Your script will read email from stdin and resend it to the real address.
You're basically describing a mail transfer agent AKA mail server. So all you need to do is a server to run it on, the required MX DNS records, and an API that allows you to configure forward addresses. Look through the documentation of the servers
listed here to see which ones offer the latter.
Just pipe all orphan email (specific to that domain) to ur PHP script and use something like this to extract the email content:
$fd = fopen("php://stdin", "r");
$email = "";
while (!feof($fd)) {
$email .= fread($fd, 1024);
}
fclose($fd);
then extract the "to" field and if it belongs to a user .. forward the email to him.If you have cPanel .. this is even easier. goto mail > default address > set default address and instead of putting an email address there put something like this
"|php -q /home/whatever/public_html/pipe.php" .. ofcourse without the quotes

Bounce Email handling with PHP?

Here is my scenario:
I have 2 email accounts: admin#domain.com and bounce#domain.com.
I want to send email to all my users with admin#domain.com but then "reply to" bounce#domain.com (until here, my PHP script can handle it).
When, the email can't be sent, it's sent to bounce#domain.com, the error message could be 553 (non existent email ...) etc.
My question is: How do I direct all those bounce emails (couldn't-sent emails) to bounce#domain.com through a handling script to check for the bounce error codes?
What programming language should I be using for the "handling script"?
What would the "handling script" look like? Can you give a sample?
in other words:
What are the procedures I should follow to handle the bounce email ?
The best scenario is be able to classify the type of bounce: soft, hard...
what we use is BounceStudio. You need to compile it and add the php libraries... not hard at all. You have the free and paid version of that product
once we detect the kind of bounce we use PEAR::MAIL::MIME to search for custom headers that we added previously to the email, lets say:
X-user-id: XXXXX
X-campaign-id: YYYYYY
X-recipient-id: SSSSSSSSS
in this way we can know the real recipient that we sent the email to.
hope this help you! so you can help me to get to the 500 points :P
Why not create a bounce#domain.com and use php to read those emails and do what ever you want?
Edit After your comment : Please chec my link whcih has a php script which will teach you how to open and email box using php and read the emails. You can use this scrip to check the error messages.
Let the emails bounce to an address that is really an emailadress (with login details etc.).
Make a php script which runs ever x minutes (for example with a cron job). This php script must do the following.
- Retrieve all email from the box (use for example Zend Mail)
- Check for the error in the message (e.g. by searching it with regular expressions)
- Do what ever is necessary.
If you want to know specifically who has bounced back you can use user specific bounce addresses. (See for example this site)
Maybe it's a little late for the answer, but you can always try something new.
I had the last week a task like this, and used BOUNCE HANDLER Class, by Chris Fortune, which chops up the bounce into associative arrays - http://www.phpclasses.org/browse/file/11665.html
This will be used after you connect to the POP3 with some mailer to get the bounces from it, then parse it into pieces with this, and if has the status you searched for, do the necessary actions.
Cheers.
If you've got a POP3 mailbox set up for bounce#domain.com, you could use a POP3 client script written in PHP to retrieve the messages and check for undeliverable messages.
You can use imap_open to access your mails from PHP.
This functions also works for POP3 but not every function may work here. However I guess in 2018 most email-clients should support IMAP.
This function can also be used to open streams to POP3 and NNTP
servers, but some functions and features are only available on IMAP
servers.
Here is a little example, how to iterate through your emails:
/* connect to server */
$hostname = "{$your-server:$your-port}INBOX";
$username = 'my-username';
$password = '123';
/* try to connect */
$inbox = imap_open($hostname,$username,$password) or die('Cannot connect to mailbox: ' . imap_last_error());
/* grab emails */
$emails = imap_search($inbox,'ALL');
/* if emails are returned, cycle through each... */
if($emails) {
/* for every email... */
foreach($emails as $email_number) {
$message = imap_body($inbox,$email_number,2);
$head = imap_headerinfo($inbox, $email_number,2);
// Here you can handle your emails
// ...
// ...
}
}
In my case, I know that I always get my mail delivery failed from Mailer-Daemon#myserver.com. So I could identify bounces like that:
if($head->from[0]->mailbox == 'Mailer-Daemon')
{
// We have a bounce mail here!
}
You said:
When, the email can't be sent, it's sent to bounce#domain.com, the
error message could be 553 (non existent email ...) etc.
So if your bounce emails have the subject "Mail delivery failed: Error 553" then you could identify them by the subject like this:
if($head->subject == 'Mail delivery failed: Error 553')
{
// We have a bounce mail here!
}
The failed email address is not in the header, so you need to parse it from the $message variable with some smart code.
You could always use something like http://cloudmailin.com to forward the bounced emails on to your php server via http however you may be better with a service dedicated to sending emails and using their api to retrieve the bounce details.
i have had pretty bad luck looking for a PHP solution for this, but i ran across this product that does just what i needed.
it runs as a native app mac/win but it does the job.
http://www.maxprog.com/site/software/internet-marketing/email-bounce-handler_sheet_us.php
I was searching for the answer to the same question. There are more parts of the question, and more options.
For handling the bounced e-mail, I found a PHP class, purely in PHP, no compile or additional software installation needed if you have a PHP powered site. It is very easy to use.
If you are using cPanel, or InterWorx/SiteWorx, you can configure some of the addresses to handle the received e-mails with a script, for example a PHP script, so you can write your own handling with the aid of the mentioned class. Or of course still you can create ordinary e-mail accounts and retrieve the mails via POP3 or IMAP, and then interpret them. I think the first one is better, because it's direct, you don't have to use additional channels, like IMAP. Of course if you can't configure your mail server, or don't know how to do it, then the former is better for you.
Good luck! :)
In the php mail command http://php.net/mail
you use the fifth parameter and add "-f" to it.
So, you use "-f mybouncebox#mydomain.com" as the parameter
the phpList newsletter manager uses this to manage bounces.
Once the bounces fill up in the mailbox, you can POP them, and process them. That's the easiest way to deal with them, as opposed to handling them when they arrive.
Here is a canned solution to process bounces using IMAP.
I changed the Return-Path header of my Mail instance to a dedicated bounce#xxxxxx.us
The only method easy enough for me to consider viable is the following, which checks via POP3 the dedicated inbox and can handle each email based on the message received.
$inst=pop3_login('mail.xxxxxx.us','110','bounce#xxxxxx.us','pass');
$stat=pop3_stat($inst);
//print_r($stat);
if($stat['Unread']>0){
echo "begin process<br><br>";
$list=pop3_list($inst);
//print_r($list);
foreach($list as $row){
if(strpos($row['from'],'MAILER-DAEMON')!==FALSE){
$msg=imap_fetchbody($inst,$row['msgno'],'1');
if(strpos($msg,'550')!==FALSE){
echo "handle hard bounce".$msg."<br><br>";
//WHATEVER HERE TO PROCESS BOUNCE
}
}
else{
$msg=imap_fetchbody($inst,$row['msgno'],'1');
echo "not from my server. could be spam, etc.".$msg."<br><br>";
//PROBABLY NO ACTION IS NEEDED
}
//AFTER PROCESSING
//imap_delete ( resource $imap_stream , int $msg_number [, int $options = 0 ] )
//commented out because I havent implemented yet. see IMAP documentation
}
}
else{
echo "no unread messages";
}
//imap_close ( resource $imap_stream [, int $flag = 0 ] )
//commented out because I havent implemented yet. see IMAP documentation.
//flag: If set to CL_EXPUNGE, the function will silently expunge the mailbox before closing, removing all messages marked for deletion. You can achieve the same thing by using imap_expunge()
function pop3_login($host,$port,$user,$pass,$folder="INBOX",$ssl=false)
{
$ssl=($ssl==false)?"/novalidate-cert":"";
return (imap_open("{"."$host:$port/pop3$ssl"."}$folder",$user,$pass));
}
function pop3_stat($connection)
{
$check = imap_mailboxmsginfo($connection);
return ((array)$check);
}
function pop3_list($connection,$message="")
{
if ($message)
{
$range=$message;
} else {
$MC = imap_check($connection);
$range = "1:".$MC->Nmsgs;
}
$response = imap_fetch_overview($connection,$range);
foreach ($response as $msg) $result[$msg->msgno]=(array)$msg;
return $result;
}
function pop3_retr($connection,$message)
{
return(imap_fetchheader($connection,$message,FT_PREFETCHTEXT));
}
function pop3_dele($connection,$message)
{
return(imap_delete($connection,$message));
}
We are using Procmail to filter these kind of mails. After examining some of the solutions already mentioned here, we ended up with a simple Procmail recipe to detect bounce messages. Depending on the accuracy you need, this might be applicable to your situation.
For details, check this blog entry.
I had the same problem, exact situation. By default my mail server, is sending all my returned mails to the same account that it was originally sent from, with automatic msg "Mail delivery failed: returning message to sender".
I dont really want to know why it was returned, had so many mails transactions that I just want to remove the bad ones. Dont have time to check specific rule such as Doestn Exist, Unavailable, etc ,,, Just want to flag for deletion and go on.
Bounce mails are so trivial as you need to deal with a lot of different servers and responses types. Each anti spam software or operating system scenario can send a different error code with the bounced email.
I recomend you to read and download this fixed debugged version of Handling Bounced Email - USING PHPMAILER-BMH AND AUTHSMTP from KIDMOSES here http://www.kidmoses.com/blog-article.php?bid=40 if you want to setup IMAP and and send your own custom headers, send them to your bounce#domain.com and then cross your fingers to see if the script catches the headers you sent written in the bounced mail. I tried it, works.
But if you want to follow my quick and easy fix that resolved my problem, here is the secret.
1 - Download the better version from KIDMOSES site or from my site, just in case KIDMOSES want to move somewhere else http://chasqui.market/downloads/KIDMOSES-phpmailer-bmh.zip
2 - The variable that contains the text of your returned mail is $body and itself contains the bad returned email (SO ITS AN MULTIDIMENSIONAL ARRAY ). (Also contains your servers mail and other DNS mails stuff, but we are looking for the BAD MAIL BOUNCED.
3 - Since your OWN SERVICE is sending you back the bounced email, then its not likely to change its format and own headers, sending back bounced emails, so you are safe to pick the order of bounced email array returned. In my case was always the same format template. (Unless you change systems or providers)
4 - We look into that $body and search for all email string variables and extract them positioning them into a two dimensional array called $matches
5 - We select the array position, by printing the array using print_r( array_values( $matches ));
6 - This is the code that you need to modify. Its around line 500 from class.phpmailer-bmh.php file
// process bounces by rules
$result = bmhDSNRules($dsn_msg,$dsn_report,$this->debug_dsn_rule);
} elseif ($type == 'BODY') {
$structure = imap_fetchstructure($this->_mailbox_link,$pos);
switch ($structure->type) {
case 0: // Content-type = text
$body = imap_fetchbody($this->_mailbox_link,$pos,"1");
$result = bmhBodyRules($body,$structure,$this->debug_body_rule);
//MY RULE IT WORKS at least on my return mail system..
$pattern = '/[a-z0-9_\-\+]+#[a-z0-9\-]+\.([a-z]{2,3})(?:\.[a-z]{2})?/i';
preg_match_all($pattern, $body, $matches);
//print_r( array_values( $matches )); //To select array number of bad returned mail desired, usually is 1st array $matches[0][0]
echo "<font color = red>".$matches[0][0]."</font><br>";
break;
So we forget about returned headers and concentrate on the bad emails. You can excel them, you can MySQL them, or process to whatever you want to do.
IMPORTANT
Comment the echos in callback_echo.php in the samples directory otherwise you get all the junk before printed.
function callbackAction ($msgnum, $bounce_type, $email, $subject, $xheader, $cheader, $remove, $rule_no=false, $rule_cat=false, $rule_msg='', $totalFetched=0) {
$displayData = prepData($email, $bounce_type, $remove);
$bounce_type = $displayData['bounce_type'];
$emailName = $displayData['emailName'];
$emailAddy = $displayData['emailAddy'];
$remove = $displayData['remove'];
//echo "<br>".$msgnum . ': ' . $rule_no . ' | ' . $rule_cat . ' | ' . $bounce_type . ' | ' . $remove . ' | ' . $email . ' | ' . $subject . ' | ';
//echo 'Custom Header: ' . $cheader . " | ";
//echo 'Bounce Message: ' . $rule_msg . " | ";
return true;
}
MY OUTPUT
Connected to: mail.chasqui.market (bounce#chasqui.market)
Total: 271 messages
Running in disable_delete mode, not deleting messages from mailbox
kty2001us#starmedia.com
...
entv#nuevoface.com
Closing mailbox, and purging messages
Read: 271 messages
0 action taken
271 no action taken
0 messages deleted
0 messages moved
You should look at SwiftMailer. It's completely written in PHP and has support for "bounce" emails.
http://swiftmailer.org/

Categories