Getting Plesk Mailbox information with PHP? - php

I have set some mail quota's on email addresses that I manage through Plesk.
However, users are complaining that they are not being informed when their inbox is full or nearly full.
So my idea was to send an email to them when their inbox is about 90% full, so I was wondering if I can retrieve mail account information using PHP?
If not, is there another way of doing this? (I'm not too familiar with console commands)

In this answer I skip the Plesk API altogether, and I assume you either store the properties of the mailboxes in a database, hardcode it, or actually use the Plesk API to retrieve it.
Here is how I retrieve the space used by a mailbox:
function getSpaceUsedByMailBox($username,$password)
{
// open mailbox
$mailBox = imap_open('{localhost:110/pop3/novalidate-cert}INBOX',$username,$password);
// test if successful
$errors = imap_errors();
if ($errors === FALSE)
{
// get info
$info = imap_mailboxmsginfo($mailBox);
// give feedback
echo "Mailbox of $username contains ".$info->Nmsgs.
' messages and is '.$info->Size.' bytes big.';
// flush notices
imap_errors();
imap_alerts();
// close mailbox
imap_close($mailBox);
// return info
return $info;
}
// change this to proper error handling
echo 'ERROR: '.print_r($errors);
// return nothing
return NULL;
}
This is just to give you an idea. You have to adapt it to your coding style.

Related

PHP Twilio - help needed to catch authentication errors

I am new to the Twilio PHP API and am finding it difficult using the sample code and even finding the correct documentation on the Twilio site to help me implement SMS messaging into our web app.
After much trial and error, and reading through some postings on this site, I have gotten far enough to figure out how to send a simple SMS message and even use a try/catch structure to deal with bad recipient phone numbers.
What I cannot for the life of me figure out is how to catch authentication errors with a client's SID and AUTH token. I'd like to catch authentication errors for a client's credentials before I try even sending messages for them. Some clients may blast a message to 200 customers so I don't want to spin my wheels if their authenticaiton fails. Heres what I have been trying:
require_once K_DOCROOT.'/includes/twilio-php-main/src/Twilio/autoload.php';
// use Twilio\Rest\Client;
// Find your Account SID and Auth Token at twilio.com/console
// and set the environment variables. See http://twil.io/secure
$sid = "ACf6eXXXGGGDDDDDDDDDDDDDDDDDDDDDDD"; // intentionally incorrect
$token = "164d3a88f753e553691960fb4d405f82";
$dest = "+15106443333"; // recipient number
try {
$twilio = new Twilio\Rest\Client($sid, $token); // Had to change this to make it work without the USE above
// $message = $twilio->messages->create($dest, // to
// [
// "body" => "Testing 123",
// "from" => "+19998887777"
// ]
// );
//
// echo "Results: ".$message->sid;
}
catch (Exception $e) {
echo $e->getCode()." : ".$e->getMessage();
}
When I run this without the $twilio->messages->create() code, I get nothing... no errors, no responses whatsoever. If I uncomment the create() section where I try and send a message, I get the following:
20003 : [HTTP 401] Unable to create record: Authentication Error - invalid username
Which makes sense. But it is forcing me to catch the authentication error when sending a message and not before.
Maybe I am missing something, but is there some way to check for authentication errors, or get back some sort of status code letting me know a client's authentication was successful or not?
Also, if you have a link to the documentation that covers error handling for Client() calls, I would greatly appreciate it.

Debugging SMTP email failures - GSuite

I am working on an eCommerce site that sends a number of emails to the customer when they complete their order using G Suite SMTP relay service. But a large number of these emails are failing. There does not seems to be any pattern to it either - sometimes all emails will send, some times just one or two, and sometimes none.
I am getting the following error: 421, "4.7.0", Try again later, closing connection.
Looking here: https://support.google.com/a/answer/3726730?hl=en doesn't really help me debug this or figure out why some emails fail.
I am using the phpmailer class (https://sourceforge.net/projects/phpmailer/)
The issue seems to occur when the first handshake fails:
function Hello($host="") {
$this->error = null; # so no confusion is caused
if(!$this->connected()) {
$this->error = array(
"error" => "Called Hello() without being connected");
return false;
}
# if a hostname for the HELO was not specified determine
# a suitable one to send
if(empty($host)) {
# we need to determine some sort of appopiate default
# to send to the server
$host = "localhost";
}
// Send extended hello first (RFC 2821)
//If this fails then the second attempt will always fail
if(!$this->SendHello("EHLO", $host))
{
//when this fails it generates the try again later error
if(!$this->SendHello("HELO", $host))
return false;
}
return true;
}
So what is the best approach for debugging this?
The error message is pretty explicit. You call a 3rd party web service, which returns an error code which says the server you are calling is at capacity, try later. Is this a free service which allows you to upgrade to a paid plan? Usually whee you see his kind of thing.

Gmail API Request Excel VBA PHP

I'm using Excel VBA to get a user's oAuth2 token for the mail.google.com scope for a native application. It works fine so I have the the user's Access Token (it refreshes if it expires) and I have the user's email address. I was using Zend SMTP to send the emails but found out there are limits to bulk sending emails this way (currently my account is locked out due to going over quota while trying to figure this out over the weekend). My client may send 2,000 emails at once and locking themselves out of their Gmail account for 24 hours is unacceptable. I think using the Gmail REST API will work, as it has higher quotas, but not finding any detailed PHP examples of how to create and send an HTML email via an HTTP request.
I know I have to create the MIME email and think I can figure that out (using this thread stackoverflow.com/questions/24940984/send-email-using-gmail-api-and-google-api-php-client) or from the Zend emails I was successfully creating. My question is what PHP code do I use to create and send the email?
The Google Dev examples all reference /userId/ (from developers.google.com/gmail/api/v1/reference/) but not sure where to get that if I just have the users token and their email address.
I assume it's something like this:
<?php
require 'GoogleAPI/src/Google/autoload.php';
extract($_POST); // use to get my client token, client's email address, the email to, cc, bcc, subject, body, etc.
//<Build the email $mime message here>
$m = new Google_Service_Gmail_Message();
$data = base64_encode($mime);
$data = str_replace(array('+','/','='),array('-','_',''),$data); // url safe
$m->setRaw($data);
$service->users_messages->send('me', $m);
?>
I don't know where to put the user's token. I know 'me' is the person that is authenticated.
I'm open to using an HTTP request as well, something like https://mywebsite.com/sendgmail.php?token=[UsersToken]&UserEmail=joe#test.com&ToEmail=toperson#xyz.com&Subject=HI&Body=Thanks for your help instead of the post method.
Just not sure how to implement that either.
I'm self taught PHP and VBA and new to the google api world so please forgive me if this is easy. I'm also looking into boxspring but trying to use the native APIs and PHP first.
EDIT:
So I've tried this using the examples but getting an error that my token is not in proper JSON format. I just want to send the token as a string. If I can't is there a way to make the string into JSON so oauth2 will accept it?:
<?php
require 'GoogleAPI/src/Google/autoload.php';
/**
* Returns an authorized API client.
* #return Google_Client the authorized client object
*/
$client = new Google_Client();
$client->setAccessToken('ya29.hwFcwk2M73vaPwNObeuwizHGjXT2y6UsAFEcDIvRAoWTM28gu2pJeK4GiMySkfAllTOQvXVMYfffff');
// Get the API client and construct the service object.
//$client = getClient();
$service = new Google_Service_Gmail($client);
// Print the labels in the user's account.
$user = 'me';
$results = $service->users_labels->listUsersLabels($user);
if (count($results->getLabels()) == 0) {
print "No labels found.\n";
} else {
print "Labels:\n";
foreach ($results->getLabels() as $label) {
printf("- %s\n", $label->getName());
}
}
?>
Error:
Fatal error: Uncaught exception 'Google_Auth_Exception' with message
'Could not json decode the token' in
/home/[my domain]/public/GoogleAPI/src/Google/Auth/OAuth2.php:179
Stack trace: #0
/home/[my domain]/public/GoogleAPI/src/Google/Client.php(215):
Google_Auth_OAuth2->setAccessToken('ya29.hwFcwk2M73...') #1
/home/[my domain]/public/labels.php(17):
Google_Client->setAccessToken('ya29.hwFcwk2M73...') #2 {main} thrown
in
/home/[my domain]/public/GoogleAPI/src/Google/Auth/OAuth2.php
on line 179
I'm sure I'm making this more difficult than it should be. I'm using the PHP example of showing a users labels, even though my final goal is to send emails.

Critical outcome when sending push notification from our server

We have an app on appstore, and with registered push notifications. They have successfully worked all the time, but we now tried to send a 'global' push, and something weird happened. This is what we have in our server-side .php file:
//Loop through tokens in tokenArray
$i = 0;
$t = 0;
foreach($tokenArray as $token)
{
$t++;
// Make notification
$msg = chr(0) . pack('n', 32) . pack('H*', $token) . pack('n', strlen($payload)) . $payload;
// Send
$result;
if($message != null)
{
$result = fwrite($fp, $msg, strlen($msg));
}
if ($result)
$i++;
}
// Close the connection to the server
fclose($fp);
if($i == 0)
{
echo 'The message was not delivered to anyone out of '.$t.'.';
}
else
{
echo 'The message was delivered to '.$i.' out of '.$t.'.';
}
The code before this has always worked, and it kind of still does. The tokenArray contains the table with tokens, as in SELECT Token FROM Tokens; from our SQL. This works.
During development, when only our own tokens were registered, it always said "The message was delivered to 4 out of 4", even though we had deleted our apps from our phones. Now we tried to send to all ≈1100 registered tokens with this code.
The message was sent, and the output was "The message was delivered to 588 out of 1194."
And we did not receive the notification ourselves!
What does that mean?
After about 5 minutes, I switched out the tokenArray with an array only containing my own tokens and sent a new push, and I received that one on my phone. I also know for a fact that the 'working' token exist in the previous 'tokenArray' which failed(I checked).
Is push notification a game of chance!? What does it mean when if($result) fails? And why did it fail over 500 times?
The certificates and .pem and .p12 etc are all working, the only thing I did different from push1 to push2 was to use another table which is a clone from the original table in my SQL-server. Table2 only have my tokens, and it worked. No other changes was made. Only SELECT Token FROM Tokens2, and later I proved that all the tokens in Tokens2 exist in Tokens
I have no idea if anyone got the push at all, or if the 'lucky' 588 of the 1200 that still has the app installed received it.
What causes this? We don't dare send another one in case half of them already received it.. Is there some limit to how fast I can send pushes at once? Or what are we doing wrong?!
Please help, thanks.
Well, I don't know php, so your code doesn't help me. However, based on your description it's likely some of the device tokens in your DB are invalid. When Apple's server gets a notification with an invalid device token it closes the socket. If you already wrote more messages after the one with the bad token, they won't reach Apple. Only after you detect that the socket was closed and open a new one your messages will reach Apple. If you don't use the enhanced notification format, it would be a good idea to start using it - this way you can get from Apple the id of the invalid message and clean your DB from invalid tokens. However, even using the enhanced format doesn't guarantee that you'll detect all the errors (unless you are willing to send the messages really slowly, and check for error responses from Apple after each message you send).
Your main loop does not take into account cases in which Apple will close socket connections. As mentioned by Eran, if you send an invalid token, Apple closes the connection at which point, any further writes using fwrite will fail. So if your 589th token is invalid, no other push will be sent to Apple.
Here's a simple fix for that that fits into your logic; this part replaces the if statement in the main loop:
if ($result) {
$i++;
} else {
fclose($fp);
// Add code here to re-open socket-connection with Apple.
}
Besides the enhanced notification format mentioned by Eran, you can also use the APNS Feedback API to query Apple for invalid tokens and purge them from your database. You can find more infomation on that here: http://bit.ly/14RPux4
There is no limit to how many push notifications you can send at once. I've sent thousands in a few seconds. The only real limitation is the connection between you and the APNS servers.

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

Categories