PHP Class COM for Outlook not open outlook - php

I have used below code for open outlook by PHP COM method. But outlook not open and it is loading & loading. no response, not open outlook, only loading & loading. Please give solution how to open outlook by PHP COM method. I have installed Office Outlook & also have MAPI.Session & also have Outlook.Application.
if (! defined ( "olMailItem" ))
{
define ("olMailItem", 0 );
}
try {
$objApp = new COM ( "Outlook.Application" ) or die ( "Cannot Load Outlook.Application" );
$namespace = $objApp->GetNamespace("MAPI");
$namespace->Logon();
$myItem = $objApp->CreateItem ( olMailItem );
$myItem->To = "yusuf.khalil88#gmail.com";
$myItem->SentOnBehalfOfName = "yusuf_khalil88#yahoo.com";
$myItem->Subject = "Hi Response me";
$myItem->Body = "I want to find out";
$myItem->Send ();
}catch ( Exception $e ) {
var_dump ( $e->getMessage () );
debug_print_backtrace ();
}

I just found another solution from this page: http://forums.devshed.com/php-development-5/php-com-automating-outlook-46167.html
Basically PHP doesn't have the constants like olMailList, so you have to refer to it by values. So to make your current script work change this line:
$myItem = $objApp->CreateItem(olMailItem);
to:
$myItem = $objApp->CreateItem(0);
That worked just fine for my situation.

Related

Mark email as read using microsoft graph api

I am writing a script that will use Microsoft Graph api ( using this library https://github.com/microsoftgraph/msgraph-sdk-php )
I managed to connect and search for the specific email, download the attachment but now I need to mark the email as read and set the flag but I have no idea how.
So far I have used this tutorial ( https://learn.microsoft.com/en-us/graph/tutorials/php?tabs=aad ) in order to connect and read the emails.
public static function getInbox() {
$token = GraphHelper::getUserToken();
GraphHelper::$userClient->setAccessToken($token);
// Only request specific properties
$select = '$select=from,isRead,receivedDateTime,subject,hasAttachments';
// Sort by received time, newest first
$orderBy = '$orderBy=receivedDateTime DESC';
$filter = '$filter=isRead eq false';
$requestUrl = '/me/mailFolders/inbox/messages?'.$filter.'&'.$select.'&'.$orderBy;
$messages = GraphHelper::$userClient->createCollectionRequest('GET', $requestUrl)
->setReturnType(Model\Message::class)
->setPageSize(100)
->getPage();
foreach ($messages as $message) {
if(strpos($message->getSubject(), 'XML')!==false ){
print('Message: '.$message->getSubject().PHP_EOL);echo PHP_EOL;
$expand="microsoft.graph.itemattachment/item";
$requestUrl = '/me/messages/'.$message->getId().'/attachments/?$expand= '.$expand;
$docDatas = GraphHelper::$userClient->createCollectionRequest('GET', $requestUrl)
->setReturnType(Model\Message::class)
->setPageSize(1)
->getPage();
$dat = $docDatas[0]->getProperties();
//parseXmlOrder(base64_decode($dat['contentBytes']));
$sendBody = array( 'isRead' => true );
var_dump( GraphHelper::$userClient->createRequest('PATCH', '/me/messages/'.$message->getId())
->attachBody($sendBody)
->execute() );
}
}
}
This is the code I have at the moment. Right at the end of the function I am trying to set the isRead attribute.
If someone could give me some advice where I am going wrong that would be amazing and help me stop banging my head against the wall.
Thanks,
Turns out giving readwrite persmissions does help. I only had read permissions.

ZeroMQ send/receive on PHP works if script launched from CLI/shell but not from APACHE/web request

I'm testing ZeroMQ for PHP. My goal is to send messages to a Python script.
Everything works fine if i launch my transmission script from PHP cli
php /path/to/myscript.php
while it fails if it's a web request. I've tried executing the server script from PHP cli as above (which seems to be the more logical way) and with a web request.
I've got a Centos 7 server with PHP 7.2 and ZeroMQ 1.1.3 installed through PECL install.
I even tried launching the above command with shell_exec/exec inside the client script but it doesn't work. Connection works fine, but it doesn't send nor receive.
Client code:
$context = new ZMQContext();
// Socket to talk to server
echo "Connecting to hello world server...\n";
$requester = new ZMQSocket($context, ZMQ::SOCKET_REQ);
$currentObject = $requester->connect("tcp://localhost:5555");
for ($request_nbr = 0; $request_nbr != 10; $request_nbr++) {
printf ("Sending request %d...\n", $request_nbr);
$risSend = $requester->send("Hello", ZMQ::MODE_NOBLOCK);
print_r($risSend);
$reply = $requester->recv();
printf ("Received reply %d: [%s]\n", $request_nbr, $reply);
}
Server Code:
$context = new ZMQContext(1);
// Socket to talk to clients
$responder = new ZMQSocket($context, ZMQ::SOCKET_REP);
$responder->bind("tcp://*:5555");
while (true) {
// Wait for next request from client
$request = $responder->recv();
printf ("Received request: [%s]\n", $request);
// Send reply back to client
$responder->send("World");
}
The browser gets stuck, without any error. Even using a timeout it reaches the limit and exits but I can't get any error message.
Ok, i finally found the solution.
Thanks to #user3666197 i managed to get an error. And it was a "permission denied" error.
With CentOS (and probably all linux sytems with SELinux) you gotta add a rule for the port used by ZMQ for the webserver.
Example:
semanage port -a -t http_port_t -p tcp 5555
OBSERVATION : The browser gets stuck, without any error.
This is pretty legal state. For it to happen, it is quite enough to "miss" the arrival of the first REQ-side-already dispatched request and due to a pleasure do depend on a distributed-Finite-State-Automaton, we fall into an unsalvageable dead-lock, where the REQ-side waits for an answer, that will never arrive (see next) and the REP-side waits for a request, that will never arrive (see the REQ-side already waiting ) and such a state remains forever that.
A best next step:
In case one has never worked with ZeroMQ,
or have never met the concept of the art of Zen-of-Zero,
one may here enjoy to first look at "ZeroMQ Principles in less than Five Seconds" before diving into further details
Start
with unconditionally working archetypes - a pair of PUSH / PULL simplex-channels, that do not require a dFSA-two-step of REQ-REP-REQ-REP-REQ-REP-...-{deadlock} ... a principally unavoidable terminal state, about which one is just never sure when it happens, but it will ... at some later time :o)
Next,
may increase a robustness of the message-flow, using zmq_setsockopt( ZMQ_IMMEDIATE, 1 ) that avoids moving messages onto incomplete connections between / among peers.
Always
prefer non-blocking forms of .recv()-methods, best with a pre-test of a message-presence with a .poll()-method. Poller-class, while available in many language-bindings is not always as handy and as flexible as using explicit .poll()-method directly on a Socket-instance.
Also feel free to read more about fine-tuning the ZeroMQ tools and other implications of the Art of the Zen-of-Zero here.
A Server-side mock-up: As a { PASS | FAIL }-proof of .send()---.recv()-delivery chain works?
<?php /* Create new PUSH-ing end */
$aCTX = new ZMQContext();
try { /* Try: things may turn wreck havoc */
$PUSHer = $aCTX->getSocket(, ZMQ::SOCKET_PUSH );
echo "POSACK'd: .getSocket() was made\n";
}
catch ( ZMQSocketException $e ){
echo " NACK'd: I told you ...\n"; /* Handle with care ... */
if ( $e->getCode() === ZMQ::ERR_... ) {
echo " - Got ERR_..., read ZeroMQ API documentation for details\n";
} else {
die( " - Get ERR: " . $e->getMessage() );
}
}
try { /* Try: things may turn wreck havoc */
$PUSHer->bind( "tcp://A.B.C.D:NNN" ); /* IP address to .connect() */
echo "POSACK'd: .bind() was made\n";
}
catch ( ZMQSocketException $e ){
echo " NACK'd: I told you ...\n"; /* Handle with care ... */
if ( $e->getCode() === ZMQ::ERR_... ) {
echo " - Got ERR_..., read ZeroMQ API documentation for details\n";
} else {
die( " - Get ERR: " . $e->getMessage() );
}
}
$retries = 1234567;
do { /* Start a loop */
try { /* Try: to PUSH.send() */
echo "Trying to send a message #" . ( 1234568 - $retries ) . "\n";
$PUSHer->send( "This is a message", ZMQ::MODE_DONTWAIT );
echo "POSACK'd: PUSHer.send() was made\n";
}
} catch ( ZMQSocketException $e ) {
echo " NACK'd: I told you ...\n"; /* Handle with care ... */
if ( $e->getCode() === ZMQ::ERR_... ) {
echo " - Got ERR_..., read ZeroMQ API documentation for details\n";
} else { /* For all ERR_... states */
die( " - Got ERR_...: " . $e->getMessage() );
}
}
/* --------------------------------------------------------------------
Here one may add an attempt to .recv( $PULLer, ZMQ::MODE_DONTWAIT );
and test for a non-empty string returned
-------------------------------------------------------------------- */
usleep( 1 ); /* Sleep a bit between operations */
} while ( --$retries );
?>
Client-side mock-up, to test the PUSH-er lives and .send()-s
import time, datetime, zmq; print( "Thissssss Sssssssssssssssssssssssssssssssssssssssnake uses ZeroMQ ver:{0:}".format( zmq.__version__ ) )
aCtx = zmq.Context()
aPull= aCtx.Socket( zmq.PULL )
aPull.setsockopt( zmq.LINGER, 0 ) # always ... be explicit
aPull_address2c = "tcp://A.B.C.D:NNN"
M0 = "{0:} try a .connect( {1:} ), if it gets to PUSH-er side"
M1 = "{0:} try a .recv(), if it gets any message"
M2 = "{0:} got a .recv()->[[[ {1:} ]]]"
M3 = "{0:} EXC'd will gracefully release resources and terminate..."
M4 = "{0:} did"
try:
print( M0.format( datetime.datetime.isoformat( datetime.datetime.now() ),
aPull_address2c
)
)
aPull.connect( aPull_address2c );
while True:
print( M1.format( datetime.datetime.isoformat( datetime.datetime.now() ) )
m = aPull.recv( zmq.NOBLOCK ) # always ... avoid blocking waits
if ( len( m ) > 0 ):
print( M2.format( datetime.datetime.isoformat( datetime.datetime.now() ),
str( m ) # always ... fused to str()
)
)
time.sleep( 5 )
else:
time.sleep( 1 )
pass
################################################################
# Here one may add an attempt to aPush.send( M4, zmq.NOBLOCK )
# and test if the reverse path aPush->$PULLer goes well
################################################################
except:
print( M3.format( datetime.datetime.isoformat( datetime.datetime.now() ) )
finally:
aPull.close() # always ... be explicit
aCtx.term() # always ... be explicit
print( M4.format( datetime.datetime.isoformat( datetime.datetime.now() ) )

How to 'console log' PHP code in Chrome or Firefox?

I've been looking up how I can debug PHP code in Chrome or Firefox but I can;t really find a solution. This is my PHP:
<?php
if(isset($_POST["data"]))
{
$var = $_POST["data"];
print "your message: " . $_POST["data"];
if(!empty($_POST['ip.data'])){
$data = $_POST['ip.data'];
$fname = mktime() . ".txt";//generates random name
$file = fopen("upload/" .$fname, 'w');//creates new file
fwrite($file, $data);
fclose($file);
}
}
?>
I want to be able to see the output of print "your message: " . $_POST["data"]; or any errors in Chrome or Firefox. I've tried Firefox Quantum that should be able to debug php? Anyways, how can I console log this?
The first step is to recognize that PHP, which is generally a server side language is a completely different context than the browser's console, which is fundamentally Javascript. Thus, to show messages to the browser's console from the server, you will need to find some way to communicate those messages (e.g., errors) to the browser.
At that point, you might consider something as simple as embedding a script tag with your PHP:
function debugToBrowserConsole ( $msg ) {
$msg = str_replace('"', "''", $msg); # weak attempt to make sure there's not JS breakage
echo "<script>console.debug( \"PHP DEBUG: $msg\" );</script>";
}
function errorToBrowserConsole ( $msg ) {
$msg = str_replace('"', "''", $msg); # weak attempt to make sure there's not JS breakage
echo "<script>console.error( \"PHP ERROR: $msg\" );</script>";
}
function warnToBrowserConsole ( $msg ) {
$msg = str_replace('"', "''", $msg); # weak attempt to make sure there's not JS breakage
echo "<script>console.warn( \"PHP WARNING: $msg\" );</script>";
}
function logToBrowserConsole ( $msg ) {
$msg = str_replace('"', "''", $msg); # weak attempt to make sure there's not JS breakage
echo "<script>console.log( \"PHP LOG: $msg\" );</script>";
}
# Convenience functions
function d2c ( $msg ) { debugToBrowserConsole( $msg ); }
function e2c ( $msg ) { errorToBrowserConsole( $msg ); }
function w2c ( $msg ) { warnToBrowserConsole( $msg ); }
function l2c ( $msg ) { logToBrowserConsole( $msg ); }
if ( 'POST' === $_SERVER['REQUEST_METHOD'] ) {
if ( isset( $_POST['data'] ) ) {
d2c( "Your message: {$_POST['data']}"
e2c( "This is an error from PHP" );
w2c( "This is a warning from PHP" );
l2c( "This is a log message from PHP" );
...
}
}
But this will be a fundamentally weak and brittle approach. I would suggest instead tailing your log files on the server directly. If you are after some color, consider using clog, lwatch, or grc:
$ grc tail -f /var/log/syslog
echo "console.log( 'Debug Objects: " . $output . "' );";
I ran through the same problem recently, just couldn't find a simple enough way without installing some large external package.
I first tried the obvious way:
<?php echo "<script>console.log(".$myVar.")<script>" ?>
but it only works with scalar types. For example:
<?php
$arr = [ 'x' => 42 ];
echo "<script>console.log(".$arr.")</script>";
?>
will output to the html
<script>console.log(Array)</script>
a solution to this is to use json_encode on the variable in the php side, then JSON.parse it in the javascript and finally console.log.
However this approach fails to capture non public properties of objects:
<?php
class Test {
private $x = 42;
public $y = 13;
}
$obj = json_encode(new Test());
echo "<script>console.log(JSON.parse('".$obj."'))</script>";
?>
will output to the browser console:
{y: 13}
Because private/protected fields can't be accessed by json_encode.
The solution here is either to add a __toString method to your class where you properly expose those fields as strings, or use some hack like calling var_export then process the output string to make it json_encode-able.
I ended up writing a small helper using the latter approach, and an output prettifier in the javascript side
Leaving the link here if anyone wants to use it.
If you want to see errors on an Ubuntu machine and you run an Apache server, you can constantly monitor and output changes to the error.log file in the apache folder with this command:
tail -f /var/log/apache2/error.log
If you have a server running on apache then this will output any errors occurred.
The tail command simply outputs the last 10 lines of a file and updates when new data is piped into the file.
I hope will help:
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
Try this
<?php
function temp()
{
if(isset($_POST["data"]))
{
$var = $_POST["data"];
print "your message: " . $_POST["data"];
if(!empty($_POST['ip.data'])){
$data = $_POST['ip.data'];
$fname = mktime() . ".txt";//generates random name
$file = fopen("upload/" .$fname, 'w');//creates new file
fwrite($file, $data);
fclose($file);
}
}
}//function
?>
<script>
console.log(".<?php temp(); ?>.");
</script>
On Chrome, you can use phpconsole which works quite well.
If anybody knows of something similar for Firefox Quantum please comment.

Php nusoap not passing content

I'm new around this corner as well as programming. I'm trying to create a web service based on nusoap and php so it passes a few values from a mysql database out.
I have looked around many websites (including stack overflow answers) and i found some solutions that i have tried but yet without success. For some reason when i do the client to access the service it always comes empty. After a day looking at this i only see letters now...
If someone could provide a way to a solution i would be much appreciated. Thank you!
Server Side
<?php
include 'nusoap.php';
$server=new nusoap_server();
$server->configureWSDL("demo"."urn:demo");
$server->register(
'gamedata',
array(),
array("estadio"=>'xsd:string',
"nome"=>'xsd:string',
)
);
function gamedata(){
$con=mysql_connect('127.0.0.1:3306', 'root', '') or die ("Erro ao conectar...");
mysql_select_db("testar",$con) or die ("Erro ao seleccionar DB...");
$queryforestadio="SELECT nome,cidade FROM estadio";
//$queryforjogos = "SELECT data, id_selecao1, id_selecao2 FROM jogo";
while($resultestadio = mysql_fetch_array($queryforestadio)){
$estadios[] = array('nome'=>$resultestadio['nome'],
'cidade'=>$resultestadio['cidade'],
);
echo "Message from function: ".$estadios['nome']['cidade'];
}
return $estadios;
}
if ( !isset( $HTTP_RAW_POST_DATA ) ) $HTTP_RAW_POST_DATA =file_get_contents( 'php://input' );
$server->service($HTTP_RAW_POST_DATA);
?>
Client Side
<?php
require('nusoap.php');
$client = new nusoap_client('http://localhost:8048/webservice/index.php');
$response= $client->call('gamedata');
$r = $response;
$count = count($r);
for($i=0; $i<=$count-1;$i++){
echo "This is name: ".$r[$i]['nome'];
echo "This is city: ".$r[$i]['cidade'];
}
This code is pointless/redundant:
$estadios[] = array('nome'=>$resultestadio['nome'],
'cidade'=>$resultestadio['cidade'],
);
You're only fetching the nome and cidade fields in your query, so $resultstadio is already an array of just those two fields and their values.
And then this does NOT match the structure you're building above:
echo "Message from function: ".$estadios['nome']['cidade'];
You probably should have something more like this:
while($resultestadio = mysql_fetch_array($queryforestadio)){
$estadios[] = $resultestadio;
echo "Message from function: ".$resultestadio['nome'] ',' . $resultestadio['cidade'];

how to make php Outlook.Application work and send mail?

if (!defined(‘olMailItem’)) define(“olMailItem”,0);
$objApp = new COM(“Outlook.Application”);
$myItem = $objApp->CreateItem(olMailItem);
$myItem->To=’xxxx#xxx.com’;
$myItem->SentOnBehalfOfName = ‘yyy#xxyyx.com’;
$myItem->Subject=”This is a test”;
$myItem->Body=”This is a Body Section now…..!”;
$myItem->Send();
i get this error
Fatal error: Uncaught exception ‘com_exception’ with message ‘ in D:\NotEncrypted\xampp\htdocs\copper\system\modules\projects\index.php on line 11251 ( ! ) com_exception: Error [0x80004004] Operation aborted in D:\NotEncrypted\xampp\htdocs\copper\system\modules\projects\index.php on line 11251
Thanks for the comments and help guys..
Most likely your Outlook Component Service is not running
run
Start -> run -> dcomcnfg.exe
To see if its there
You also need to check your windows Registry if MAPI.Session is available
Start -> Run -> HKEY_CLASSES_ROOT -> Outlook.Application -> MAPI.Session
If you can't find this then use this tutorials
http://www.digiways.com/articles/php/outlook/
Example
set_time_limit(10);
if (! defined ( "olMailItem" ))
{
define ("olMailItem", 0 );
}
try {
$objApp = new COM ( "Outlook.Application" ) or die ( "Cannot Load Outlook.Application" );
$namespace = $objApp->GetNamespace("MAPI"); // or MAPI.Session
$namespace->Logon();
$myItem = $objApp->CreateItem ( olMailItem );
$myItem->To = "xxxx#xxx.com";
$myItem->SentOnBehalfOfName = "yyy#xxyyx.com";
$myItem->Subject = "This is a test";
$myItem->Body = "This is a Body Section now…..!";
$myItem->Send ();
} catch ( Exception $e ) {
var_dump ( $e->getMessage () );
debug_print_backtrace ();
}
I hope it helps
I just found another solution from this page: http://forums.devshed.com/php-development-5/php-com-automating-outlook-46167.html
Basically PHP doesn't have the constants like olMailList, so you have to refer to it by values. So to make your current script work change this line:
$myItem = $objApp->CreateItem(olMailItem);
to:
$myItem = $objApp->CreateItem(0);
That worked just fine for my situation.

Categories