SwiftMailer Batch email times my Server out - php

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.

Related

How to send sms messages using twilio and windows scheduler?

I would like to schedule when I send sms messages using Twilio. I currently can schedule when to run php scripts using Windows Scheduler, however, whenever I try to send messages using twilio, the script doesn't execute.
PHP script that sends sms text message via using twilio
<?php
// Required if your environment does not handle autoloading
include '../vendor/autoload.php';
// Use the REST API Client to make requests to the Twilio REST API
use Twilio\Rest\Client;
// Your Account SID and Auth Token from twilio.com/console
$sid = 'XXXXXXXXXXXXXXXXXXXXXXXXX';
$token = 'XXXXXXXXXXXXXXXXXXXXXXXXXX';
$client = new Client($sid, $token);
// Use the client to do fun stuff like send text messages!
$client->messages->create(
// the number you'd like to send the message to
'+19894837813',
array(
// A Twilio phone number you purchased at twilio.com/console
'from' => '+19823837823',
// the body of the text message you'd like to send
'body' => 'Hey Jenny! Good luck on the bar exam!'
)
);
?>
VB script that references batch file
Set WinScriptHost = CreateObject("WScript.Shell")
WinScriptHost.Run Chr(34) & "C:\xampp\htdocs\Twilio\php\script.bat" & Chr(34), 0
Set WinScriptHost = Nothing
Batch file that calles php script
"C:\xampp\php\php.exe" -f "C:\xampp\htdocs\Twilio\php\index.php"

ActiveMQ not returning message when queue has n number of pending messages

Environment/Background:
Using PHP Stomp library to send and receive message from ActiveMQ (v5.4.3).
Steps:
Client sends a message with reply-to & correlation-id headers to request queue (say /queue/request)
Subscribe to the response queue (say /queue/response)
Read frame
ack
unsubscribe
The above steps works fine when there is no pending message or pending message < n. In my case, n =200. When the number of pending message is > 200, the message is not delivered. The process waits till timeout and finally timeout without response. I can see the message (using admin UI) after timeout. Here is the code that I'm using for this case:
<?php
// make a connection
$con = new Stomp("tcp://localhost:61616");
// Set read timeout.
$con->setReadTimeout(10);
// Prepare request variables.
$correlation_id = rand();
$request_queue = '/queue/com.domain.service.request';
$response_queue = '/queue/com.domain.service.response';
$selector = "JMSCorrelationID='$correlation_id'";
$headers = array('correlation-id' => $correlation_id, 'reply-to' => $response_queue);
$message = '<RequestBody></RequestBody>';
// send a message to the queue.
$con->send($request_queue, $message, $headers);
// subscribe to the queue
$con->subscribe($response_queue, array('selector' => $selector, 'ack' => 'auto'));
// receive a message from the queue
$msg = $con->readFrame();
// do what you want with the message
if ( $msg != null) {
echo "Received message with body\n";
var_dump($msg);
// mark the message as received in the queue
$con->ack($msg);
} else {
echo "Failed to receive a message\n";
}
unset($con);
Other findings:
Sending messages from one file (say from sender.php) and receive using another script (say receiver.php) working fine.
Allows to send more than 1000 message in the same request queue(and eventually processed and placed in response queue). So it doesn't look like memory issue.
Funny enough, while waiting for timeout, if I browse the queue on admin UI, I get the response.
By default, the stomp broker that I use set the prefetch size to 1.
Without knowing more my guess is that you have multiple consumers and one is hogging the messages in it's prefetch buffer, the default size is 1000 I think. To debug situations like this it's usually a good idea to look at the web console or connect with jconsole and inspect the Queue MBean to see the stats for in-flight messages, number of consumers etc.
Answering my own question.
The problem I'm facing is exactly what is described in http://trenaman.blogspot.co.uk/2009/01/message-selectors-and-activemq.html and the solution is to increase the maxPageSize as specified in ActiveMQ and maxPageSize
As you can match that the 200 is not a varying number, but the default value of maxPageSize.
More references:
http://activemq.2283324.n4.nabble.com/Consumer-is-not-able-to-pick-messages-from-queue-td2531722.html
https://issues.apache.org/jira/browse/AMQ-2217
https://issues.apache.org/jira/browse/AMQ-2745

Collect data from email message

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

SMPP connection

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);
}
});

smtp callback on new email

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

Categories