Auto read and send email variable - php

I need to read an email and then send a value in that email into another page. I've successful to read email and detect subject and date of that email. After read that incoming email, I need to send that value into another php page whoch in that page I can do background process.
Here's the code to read email
include "connect.php";
$mailbox = imap_open("{mail.xxxxx.com:143/novalidate-cert}INBOX", "username", "password"); //Note 1
$count = imap_num_msg($mailbox);
$headers = imap_headerinfo($mailbox, $count);
$sub = $headers->subject;
$time = $headers->date;
$pieces = explode("://",$sub);
$check = mysql_query("SELECT * FROM email WHERE web='$pieces[1]' AND date='$time'");
$data = mysql_fetch_array($check);
if($time != $date['date']) {
//code to send parameter here
echo "enter";
} else {
echo "no";
}
I need to send an email subject and email date into another php page. What ways can be used ? Is that with javascript, ajax or what ?
Thanks for your help,

Related

Why is this script sending blank emails without using template in SugarCRM?

This is my code to send emails in SugarCRM CE 6.5.x version,
<?php
if (!defined('sugarEntry') || !sugarEntry) die('Not A Valid EntryPoint');
require_once('include/SugarPHPMailer.php');
$msg = new SugarPHPMailer();
$emailObj = new Email();
$defaults = $emailObj->getSystemDefaultEmail();
//Setup template
require_once('XTemplate/xtpl.php');
$xtpl = new XTemplate('custom/modules/Users/ChangePassword.html');
//assign recipients email and name
$rcpt_email = 'sohan.tirpude#mphasis.com';
$rcpt_name = 'Sohan';
//Set RECIPIENT's address
$email = $msg->AddAddress($rcpt_email, $rcpt_name);
//Send msg to users
$template_name = 'User';
//Assign values to variables in template
$xtpl->assign('EMAIL_NAME', $rcpt_name);
$xtpl->parse();
//$body = "Hello Sohan, It's been 80 days that you haven't changed your password. Please take some time out to change password first before it expires.";
$msg->From = $defaults['email'];
$msg->FromName = $defaults['name'];
$msg->Body = from_html(trim($xtpl->text($template_name)));
//$msg->Body = $body;
$msg->Subject = 'Change Password Request';
$msg->prepForOutbound();
$msg->AddAddress($email);
$msg->setMailerForSystem();
//Send the message, log if error occurs
if (!$msg->Send()){
$GLOBALS['log']->fatal('Error sending e-mail: ' . $msg->ErrorInfo);
}
?>
Now this script send blanks emails, and when I hardcoded body part then it is takes those message written in body, and sends an email. So, please help me here.

PHP Sleep Is Breaking Foreach

I have this following code:
<?php
$participants_db = "test_test_test_test_test_test_Sticky_Sticky_Sticky_Sticky_";
$participants = array_unique(explode("_", $participants_db));
foreach($participants as $user)
{
echo $user . '\n';
sleep(10);
}
?>
I spent hours debugging this script, it actually get each username and send email to each one,
the thing is it was sending emails for each user but $user didn't change... Im wondering Why Sleep Break the Foreach and How to fix this..
http://3v4l.org/b048m
UPDATE
here's the Full Code:
foreach($participants as $user)
{
if($user == '')
{
//echo 'broken';
break 1;
}
//get each user's email address
$sql3 = $dbh->prepare("SELECT * FROM users WHERE username = ?");
$sql3->execute(array($user));
while($a = $sql3->fetch())
{
$email = $a['email'];
$username = $a['username'];
}
$message = str_replace("{USERNAME}", $username.'_'.$user, $message);
sendemail($email, $cc, $from, $subject, $message, $filename, $filepath);
//sleep(10);
}
the array (participants) contains usernames , each user has different email address.
this script gets executed by a cron job. after the execution it sent emails to 2 emails (for example), and it's saying Hello Test_test to Both Emails That have Different Usernames
Im just wondering, how did it get the email and the username still the same???
The problem was str_replace
it replaced the {USERNAME} with a username, then after the exection $message doesn't contain {USERNAME} Which caused the main problem of it...

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.

Creating a Craigslist Anonymous Email Forwarding Program

The following program is intended to match incoming email aliases with those in the database, and forward the email to the right address, like Craigslist does.
I am now getting this error:
Error: [1] You must provide at least one recipient email address.
in anon-email.php at line number: sending the email
Here is the code:
$mailboxinfo = imap_mailboxmsginfo($connection);
$messageCount = $mailboxinfo->Nmsgs; //Number of emails in the inbox
for ($MID = 1; $MID <= $messageCount; $MID++)
{
$EmailHeaders = imap_headerinfo($connection, $MID); //Save all of the header information
$Body = imap_qprint(imap_fetchbody($connection, $MID, 1)); //The body of the email to be forwarded
$MessageSentToAllArray = $EmailHeaders->to; //Grab the “TO” header
$MessageSentToAllObject = $MessageSentToAllArray[0];
$MessageSentToMailbox = $MessageSentToAllObject->mailbox ."#". $MessageSentToAllObject->host; //Everything before and after the “#” of the recipient
$MessageSentFromAllArray = $EmailHeaders->from; //Grab the “FROM” header
$MessageSentFromAllObject = $MessageSentFromAllArray[0];
$MessageSentFromMailbox = $MessageSentFromAllObject->mailbox ."#". $MessageSentFromAllObject->host; //Everything before and after the “#” of the sender
$MessageSentFromName = $MessageSentFromAllObject->personal; //The name of the person who sent the email
$toArray = searchRecipient($MessageSentToMailbox); //Find the correct person to send the email to
if($toArray == FALSE) //If the alias they entered doesn’t exist…
{
$bounceback = 'Sorry the email in your message does not appear to be correct';
/* Send a bounceback email */
$mail = new PHPMailer(); // defaults to using php “mail()”
$mail -> ContentType = 'text/plain'; //Plain email
$mail -> IsHTML(false); //No HTML
$the_body = wordWrap($bounceback, 70); //Word wrap to 70 characters for formatting
$from_email_address = 'name#domain.com';
$mail->AddReplyTo($from_email_address, "domain.Com");
$mail->SetFrom($from_email_address, "domain.Com");
$address = $MessageSentFromMailbox; //Who we’re sending the email to
$mail->AddAddress($address, $MessageSentFromName);
$mail->Subject = 'Request'; //Subject of the email
$mail->Body = $the_body;
if(!$mail->Send()) //If the mail fails, send to customError
{
customError(1, $mail->ErrorInfo, "anon-email.php", "sending the email");
}
}
else //If the candidate address exists, forward on the email
{
$mail = new PHPMailer(); // defaults to using php “mail()”
$mail -> ContentType = 'text/plain'; //Plain E-mail
$mail -> IsHTML(FALSE); //No HTML
$the_body = wordwrap($Body, 70); //Wordwrap for proper email formatting
$from_email_address = "$MessageSentFromMailbox";
$mail->AddReplyTo($from_email_address);
$mail->SetFrom($from_email_address);
$address = $toArray[1]; //Who we’re sending the email to
$mail->AddAddress($address, $toArray[0]); //The name of the person we’re sending to
$mail->Subject = $EmailHeaders->subject; //Subject of the email
$mail->Body = ($the_body);
if(!$mail->Send()) //If mail fails, go to the custom error
{
customError(1, $mail->ErrorInfo, "anon-email.php", "sending the email");
}
}
/* Mark the email for deletion after processing */
imap_delete($connection, $MID);
}
imap_expunge($connection); // Expunge processes all of the emails marked to be deleted
imap_close($connection);
function searchRecipient() // function to search the database for the real email
{
global $MessageSentToMailbox; // bring in the alias email
$email_addr = mysql_query("SELECT email FROM tbl WHERE source='$MessageSentToMailbox'"); // temp store of the real email
$row = mysql_fetch_array($email_addr); //making temp store of data for use in program
if(empty($row['email']))
{
return FALSE;
}
else /* Else, return find the person's name and return both in an array */
{
$results = mysql_query("SELECT * FROM tbl WHERE email = '$email_addr'"); // temp store of both queries from this function
$row = mysql_fetch_array($results, $email_addr); //making temp store of data for use in program
$name = $row['author']; // taking the author data and naming its variable
return array($name, $email_addr); // this is the name and the real email address to be used in function call
}
}
function customError($errno, $errstr, $file, $line)
{
error_log("Error: [$errno] $errstr in $file at line number: $line",1, "name#domain.com","From: name#domain.com.com");
die();
}
Here is the first thing I would try:
It would appear that your function searchRecipient isn't being passed a parameter. Rather than use the global keyword, I would define it in your function call. Also, mysql_fetch_array does not pass back an associative array, which is what you are using in your next step. I would change that to mysql_fetch_assoc (it's the same thing essentially). There are also a few other minor syntax corrections in this function. Here are my proposed changes to that function. I think this should fix your problem. Or at least get you moving forward.
function searchRecipient($MessageSentToMailbox) // function to search the database for the real email
{
$email_addr = mysql_query("SELECT email FROM tbl WHERE source='$MessageSentToMailbox'"); // temp store of the real email
$row = mysql_fetch_assoc($email_addr); //making temp store of data for use in program
if(empty($row['email']))
{
return FALSE;
}
else /* Else, return find the person's name and return both in an array */
{
$email_addr = $row['email'];
$results = mysql_query("SELECT * FROM tbl WHERE email = '$email_addr'"); // temp store of both queries from this function
$row = mysql_fetch_assoc($results); //making temp store of data for use in program
$name = $row['author']; // taking the author data and naming its variable
return array($name, $email_addr); // this is the name and the real email address to be used in function call
}
}
You could also combine this into one query and make it a little easier. Here is that solution.
function searchRecipient($MessageSentToMailbox)
{
$results = mysql_query("SELECT email, author FROM tbl WHERE source='$MessageSentToMailbox'");
$row = mysql_fetch_assoc($results);
if(empty($row['email']) || empty($row['author'])) return false;
return array($row['email'], $row['author']);
}

Retrieve the 3 most recent email using imap and php

I'm trying to figure out how to get the latest 3 emails (SEEN and UNSEEN) using imap and php. It need to be ressource-efficient since the mailbox as 1 000 emails inside. Getting all header may need too much ressources I think.
I just need the sender, the subject and the date...
Any idea? Thanks for any syggestion/help/explaination/hint...
I did it like that:
$mbox = imap_open("{imap.myconnection.com:993/imap/ssl}INBOX", "username", "password");
// get information about the current mailbox (INBOX in this case)
$mboxCheck = imap_check($mbox);
// get the total amount of messages
$totalMessages = $mboxCheck->Nmsgs;
// select how many messages you want to see
$showMessages = 5;
// get those messages
$result = array_reverse(imap_fetch_overview($mbox,($totalMessages-$showMessages+1).":".$totalMessages));
// iterate trough those messages
foreach ($result as $mail) {
print_r($mail);
// if you want the mail body as well, do it like that. Note: the '1.1' is the section, if a email is a multi-part message in MIME format, you'll get plain text with 1.1
$mailBody = imap_fetchbody($mbox, $mail->msgno, '1.1');
// but if the email is not a multi-part message, you get the plain text in '1'
if(trim($mailBody)=="") {
$mailBody = imap_fetchbody($mbox, $mail->msgno, '1');
}
// just an example output to view it - this fit for me very nice
echo nl2br(htmlentities(quoted_printable_decode($mailBody)));
}
imap_close($mbox);
PHP-Ref IMAP: http://php.net/manual/en/ref.imap.php
Regards
Dominic
What about
imap_search($res, 'RECENT');
?
http://php.net/manual/en/function.imap-search.php
$msgnos = imap_search($mbox, "UNSEEN", SE_UID);
$i=0;
foreach($msgnos as $msgUID) {
$msgNo = imap_msgno($mbox, $msgUID);
$head = imap_headerinfo($mbox, $msgNo);
$mail[$i][] = $msgUID;
$mail[$i][] = $head->Recent;
$mail[$i][] = $head->Unseen;
$mail[$i][] = $head->from[0]->mailbox."#".$head->from[0]->host;
$mail[$i][] = utf8_decode(imap_utf8($head->subject));
$mail[$i][] = $head->udate;
}
return $mail;
imap_close($mbox);
Will do the job.

Categories