I have a custom app that i built which relies on a cron job to check for new email every 5 minutes. If there is a new email it then performs an action. What I would like to do is have a callback fired off when a new email arrives and then perform the action.
I could set the cron job to 1min intervals ( currently it is set to 5min ) but this seems like a waste of resources. The app is built in php and any help would be appreciated, i am just not sure what direction i should be looking at them moment.
M
You could use something like MailGun or SendGrid's Parse API which will receive your email for you and callback to an endpoint you specify.
very basic mail pipe script:
#!/usr/bin/php -q
<?php
// read from stdin
$fd = fopen("php://stdin","r");
$email = "";
while ( !feof($fd) ){
$email .= fread($fd,1024);
}
fclose($fd);
?>
what you do with $email, depends on what you need
Related
I know it's somehow weird to ask something like this, but I'm trying to program a telegram bot with PHP.
The bot is in a channel (e.g. Channel A) and I'm going to send messages in that channel, so the bot will copy X number of messages to another channel (Channel B), Every Y minutes.
Example:
X = 5
Y = 60
Channel A = ID .....
Channel B = ID .....
So it will COPY 5 messages from A to B every hour...
Can anybody write me a template please? I think I can configure the VPS and webhook stuff (SSL and etc).
If you need send message per minutes, and get message from Telegram callback, you need read about queue (zmq, redis, gearman or etc).
Create daemons. These are your bots. They can read messages from queue and send callbacks.
Write Controller to get callback from telegram. It can take message and push to queue.
Install Ev or Event extension on PHP. (You can use reactphp, it simple solution to create timer)
Bot1 create timer, and listen messages. If we have more 5 messages, timer can push message in queue for Bot2.
You can use reactphp/zmq, nrk/predis-async to helpful your task
P.S. It is most simple solution. But you can use pthreads (instead create daemon process) or use simple socket to send message in bot.
If you want to use webhook things you can do this.
write a sample code like this:
<?php
$texts_from_other_channel = [];
array_push($texts_from_other_channel , $update_array['message']['text']);
$t_size = sizeof($texts_from_other_channel)
for($i=0 ; $i < $t_size ; $i++){
$post_prs = ['chat_id' => $channel_id , 'text' => $texts_from_other_channel[$i]];
send_reply($sendmessag_url , $post_prs);
end
?>
other things like send_reply() function or $update_array are up to you and I left to yourself.
i run php to send email list using third party smtp. I want to show Receipt(TO:) with my customer email. So i need to loop call php email function follow:
$emailList = explode("\n",file_get_contents('/list1.txt'));
foreach ($emailList as &$value) {
$email = new Email();
$email->setFrom("info#xxx.net");
$email->setToList($value);
$email->setSubject("360’s Got Talent");
$email->setHtmlContent($str);
$apiClient = new ApiClient("edm#xxx.net", "xxx");
$response = $turboApiClient->sendEmail($email);
var_dump($response);
echo ":: $value has been sent.<br />";
}
unset($value);
Is it standard way to do ?
Are there anyway to sent one time but can show TO: one by one ?
because when I run this, PHP is waiting total process and then writing report (echo). Sometime server is showing 504 Gateway Timeout.
or Can I make PHP run one by one ? report every line once it done, not waiting the whole process like a batch process.
Please guide.
I want to collect data from email to mysql database using php.
If some one is sent a mail to their mail account to my mail id. I want that mail information to store in my database. for further operation. It is possible in PHP because I saw this feature in one hosting support application Kayako Fusion which developed by PHP.
So plese give some information to do this task.
If you want to parse with PHP the best way is to use a 3rd party API to revive the email and then send it to your PHP script with a HTTP Post.
I'd recommend using either sendgrid.com or mailgun.com
Both of these services will parse the email and send you the information in a http POST that you can then insert into mysql. API docs for both: MailGun Incoming Parse API / SendGrid Incoming Parse API
You can use the imap functions, for example:
<?php
$imap = imap_open("{server.example.com:143}INBOX" , 'login' , 'password');
if( $imap ) {
//Check no.of.msgs
$num = imap_num_msg($imap);
//if there is a message in your inbox
if( $num >0 ) {
//read that mail recently arrived
$the_message = imap_body($imap, $num);
//Do the stuff with $the_message
}
//close the stream
imap_close($imap);
}
You'll have to setup a cronjob (scheduled task on Windows) that connects to the Exchange or POP server, retrieve's all new emails sinds the last run and insert them into the DB.
In case of a POP mail server(I think POP will be easier), there is a comment here with all functions you need right -> here. If that doesn't work, try Googling for "PHP POP wrapper" or something similar.
In case of a Microsoft Exchange server, you'd have to use a PHP Exchange wrapper, found one here for you.
Goodluck!
You can pipe your email to a php script and then extract each part of email and store it in data base.
check this example
when you get content of email you can do what ever you want
I'm establishing an SMPP connection via PHP using this free library. To receive a message, I'm using the following code, given in the example:
<?php
$GLOBALS['SMPP_ROOT'] = dirname(__FILE__); // assumes this file is in the root
require_once $GLOBALS['SMPP_ROOT'].'/protocol/smppclient.class.php';
require_once $GLOBALS['SMPP_ROOT'].'/transport/tsocket.class.php';
// Construct transport and client
$transport = new TSocket('your.smsc.com',2775);
$transport->setRecvTimeout(60000); // for this example wait up to 60 seconds for data
$smpp = new SmppClient($transport);
// Activate binary hex-output of server interaction
$smpp->debug = true;
// Open the connection
$transport->open();
$smpp->bindReceiver("USERNAME","PASSWORD");
// Read SMS and output
$sms = $smpp->readSMS();
echo "SMS:\n";
var_dump($sms);
// Close connection
$smpp->close();
?>
It works perfectly well, when I run the script in the browser window and send the SMS from my phone within given 60 seconds, but I don't quite understand how to make it work for a long time. I mean, like in real-life situation, when it should run on the background and trigger some events when receiving an SMS. How do I do that? Because now, I need to refresh the page every time to get an SMS, and it only works once. Thanks in advance.
If your solution needs to run within a browser, you shouldn't connect to the SMPP server directly from your script. It would lead to a single user scenario.
You should put a endless loop around the readSMS call and make it a console application which runs as a daemon. Then you write the result of readSMS into a database and read this from your web application. With this you could use html refresh or some fancy ajax querying the database and presenting the incoming sms.
Usually SMPP receiver connections run in blocking mode on the socket (no timeout), because either you receive either a SMS, or an enquire_link (which needs to be answered by a enquire_link_resp - your library does this automatically). Whenever you read a SMS, process it (put it in the database) and call readSMS again - it will block until the next SMS comes in.
You can try this.
<?php
set_time_limit(0);
$GLOBALS['SMPP_ROOT'] = dirname(__FILE__); // assumes this file is in the root
require_once $GLOBALS['SMPP_ROOT'].'/protocol/smppclient.class.php';
require_once $GLOBALS['SMPP_ROOT'].'/transport/tsocket.class.php';
// Construct transport and client
$transport = new TSocket('your.smsc.com',2775);
$transport->setRecvTimeout(60000); // for this example wait up to 60 seconds for data
$smpp = new SmppClient($transport);
// Activate binary hex-output of server interaction
$smpp->debug = true;
// Open the connection
$transport->open();
$smpp->bindReceiver("USERNAME","PASSWORD");
while(1) {
// Read SMS and output
$sms = $smpp->readSMS();
echo "SMS:\n";
var_dump($sms);
}
// Close connection
$smpp->close();
?>
Try to use another library
composer require glushkovds/php-smpp
To receive sms:
<?php
require_once 'vendor/autoload.php';
$service = new \PhpSmpp\Service\Listener(['your.smsc.com'], 'login', 'pass');
$service->listen(function (\PhpSmpp\SMPP\Unit\Sm $sm) {
if ($sm instanceof \PhpSmpp\Pdu\DeliverSm) {
var_dump($sm->message);
}
});
I realise that batchEmail is no longer part of the new SwiftMailer. So I made this script:
<?
//
// GC PRESS EMAILER v5
//
ini_set('display_errors',1);
error_reporting(E_ALL);
require_once("config.php");
include_once("hawkmail/mail/lib/swift_required.php");
$c=mysql_connect($dbh,$dbu,$dbp);
function SendEmail(){
// DB
$s=mysql_query("SELECT * FROM `newgc`.`press_list`");
// Process Color Listing Loop
while($r=mysql_fetch_array($s)){
// ###########################
// START LOOP
// ###########################
$name=$r['name'];
$email=$r['email'];
$to=array(''.$email.''=>''.$name.'');
include("hawkmail/templates/press.php");
# Email subject
$str=$name;
$str=substr($str, 0, strrpos($str, ' '));
$subject='Dear '.$str.', you are invited to our Exclusive Party Collection Press Day!';
# send message
include("hawkmail/settings.php");
}
// ###########################
// END LOOP
// ###########################
}
SendEmail();
?>
The database has 200 records. And I ran the script and it sends a few emails and then times out
504 Gateway Time-out
The name and email records are like
John Smith
John.smith#site.com
Very plain. And my hawkmail/settings.php is this:
# mail
$smpturl="smtp.sendgrid.net";
$mailu="sitesitesite";
$mailp="sitessssssssssss";
$from=array("no-reply#site.com"=>"site.com");
# login credentials & setup Swift mailer parameters
$transport=Swift_SmtpTransport::newInstance($smpturl, 587);
$transport->setUsername($mailu);
$transport->setPassword($mailp);
$swift=Swift_Mailer::newInstance($transport);
# create a message (subject)
$message=new Swift_Message($subject);
# attach the body of the email
$message->setFrom($from);
$message->setBody($html, 'text/html');
$message->setTo($to);
$message->addPart($text, 'text/plain');
# actually send the message
if($recipients=$swift->send($message, $failures)){}else{}
Is there anyway to increase the limit of PHP time out (I use Ubuntu and Nginx) or is there an alternative to BatchMail() really don't understand why it was removed.
Can someone post examples of Batch mail scripts using the new swiftmailer?
Sending emails is the most complicated thing to do online.
It is the second most used service and the most abused.
I built my own custom email platform for sending bulk emails.
The timeout you experience is because of the Apache and PHP execution limits.
You need to run it as a CLI application with set_time_limit (0);
php /path/to/app/script.php something like this straight in the console.
If you do not have SSH access then run it with shell_exec like this:
shell_exec("php /path/to/app/script.php > /dev/null 2>/dev/null &");
This will ensure that the script that calls it does not hang around till it finishes.