Updating an email's subject using Microsoft Graph in PHP - php

Here's my current code:
require_once '/pathtovendor/vendor/autoload.php';
use Microsoft\Graph\Graph;
use Microsoft\Graph\Model;
use Microsoft\Graph\Http\GraphRequest;
$access_token = "My valid access token";
$graph = new Graph();
$graph->setAccessToken($access_token);
$reply = array( "Comment" => "My reply" );
$message_id = "Valid message ID";
if($graph->createRequest("POST", "/me/messages/".$message_id."/reply")
->attachBody($reply)
->execute()){
// I can get to this part OK. Message is replied to.
//This code doesn't work
$graph->createRequest("PATCH", "/me/messages/".$message_id)
->attachBody(array( "Subject" => "New Subject" ))
->execute();
}
I can run GET and POST requests which work, but I can't get PATCH to work this way. It continues to throw a 500 Internal Server Error. Any help is appreciated.

This is only supported on draft messages. From the documentation:
subject | String |
The subject of the message. Updatable only if isDraft = true.
The following properties can only be updated in draft messages:
bccRecipients
body
ccRecipients
internetMessageId
replyTo
sender
subject
toRecipients
from

Related

Mandrill PHP library - FROM field

How can I set a proper FROM field for the PHP Mandrill library?
In Java, I can use:
from = "Some Description <noreply#domain.com>";
If I try the same in PHP, I get an error:
Validation error: {"message":{"from_email":"The username portion of the email address is invalid (the portion before the #: Some Description
Only emails with FROMs like this get through:
$from = "noreply#domain.com";
In case it matters, here's how I send an email:
$from = "Some Description <noreply#domain.com>";
$message = array("subject" => $aSubject, "from_email" => $from, "html" => $aBody, "to" => $to);
$response = $mandrill->messages->send($message, $async = false, $ip_pool = null, $send_at = null);
If you read the documentation https://mandrillapp.com/api/docs/messages.html it has two parameters in request
from_email and from_name when we pass
$from = "Name <email>",
It is not accepted by mandrill hence it throws error , To pass a name you need to pass from_name with name value.

How to get LINE user mid using PHP SDK?

I use the LINE BOT API Trial SDK PHP (https://github.com/line/line-bot-sdk-php).
But, for this method:
$res = $bot->sendText(['TARGET_MID'], 'Message');
How to get the user's MID to send them a message?
Thanks for help.
1) A very quick way to get the mid of an interactive user (more of a fun hack, really) is to register a callback URL as per the API instructions, then capture the POST data to that URL like so:
// /callback/index.php
<?php
$postdata = file_get_contents("php://input");
#file_get_contents('https://'.$_SERVER['SERVER_NAME'].'/LINE/' . json_encode($postdata));
Next, scan the QR code in the channel console and add your trial bot to your LINE account. After that is done, send it a quick "Hello!" text.
You could then save the POST data to a text file if you wish, or you could check the server logs. For example, you might see something like this:
163.128.118.223 - - [03/Sep/2016:07:25:25 -0700] "POST /line/callback/ HTTP/1.1" 200 - "-" "ChannelEventDispatcher/1.0"
106.152.218.107 - - [03/Sep/2016:07:25:25 -0700] "GET /LINE/{\"result\":[{\"content\":{\"toType\":1,\"createdTime\":1472114754839,\"from\":\"ub7dbd4a12c322f6c0117773d739c55a4\",\"location\":null,\"id\":\"4357194057879\",\"to\":[\"u2b6a4ba287028dee7291122094dac827\"],\"text\":\"Hello!\",\"contentMetadata\":{\"AT_RECV_MODE\":\"2\",\"SKIP_BADGE_COUNT\":\"true\"},\"deliveredTime\":0,\"contentType\":1,\"seq\":null},\"createdTime\":1472912724868,\"eventType\":\"138311609000106301\",\"from\":\"u236d23c2e36bd87217655609a1c31cb8\",\"fromChannel\":1241102815,\"id\":\"WB1519-3102846635\",\"to\":[\"u2b6a4ba287028dee7291122094dac827\"],\"toChannel\":1462261375}]} HTTP/1.1" 404 15 "-" "-"
The \"from\":\"ub7dbd4a12c322f6c0117773d739c55a4\" is the pertinent part.
2) If you'd like to get started with receiving messages, you can start like this as your callback script. Simply send your BOT the message 'mid' and it should respond with your mid.
Here is a starting callback script I made with signature verification included for you.
// /callback/index.php
<?php
// Show all errors for testing
error_reporting(E_ALL);
// SDK is installed via composer
require_once __DIR__ . "/includes/vendor/autoload.php";
use LINE\LINEBot;
use LINE\LINEBot\HTTPClient\GuzzleHTTPClient;
// Set these
$config = [
'channelId' => LINE_CHANNEL_ID,
'channelSecret' => LINE_CHANNEL_SECRET,
'channelMid' => LINE_CHANNEL_MID,
];
$sdk = new LINEBot($config, new GuzzleHTTPClient($config));
$postdata = #file_get_contents("php://input");
$messages = $sdk->createReceivesFromJSON($postdata);
// Verify the signature
// REF: http://line.github.io/line-bot-api-doc/en/api/callback/post.html#signature-verification
$sigheader = 'X-LINE-ChannelSignature';
// REF: http://stackoverflow.com/a/541450
$signature = #$_SERVER[ 'HTTP_'.strtoupper(str_replace('-','_',$sigheader)) ];
if($signature && $sdk->validateSignature($postdata, $signature)) {
// Next, extract the messages
if(is_array($messages)) {
foreach ($messages as $message) {
if ($message instanceof LINEBot\Receive\Message\Text) {
$text = $message->getText();
if ($text == "mid") {
$fromMid = $message->getFromMid();
// Send the mid back to the sender and check if the message was delivered
$result = $sdk->sendText([$fromMid], 'mid: ' . $fromMid);
if(!$result instanceof LINE\LINEBot\Response\SucceededResponse) {
error_log('LINE error: ' . json_encode($result));
}
} else {
// Process normally, or do nothing
}
} else {
// Process other types of LINE messages like image, video, sticker, etc.
}
}
} // Else, error
} else {
error_log('LINE signatures didn\'t match');
}

check if domain exists using PHP PEAR Mail class

I noticed that my server has been returning this error when trying to send email to an invalid domain:
Standard Message: Failed to set sender: user#invaliddomain.coom [SMTP: Invalid response code received from server (code: 553, response: 5.1.8 ... Domain of sender address user#invaliddomain.coom does not exist)]
Standard Code: 10004
DBMS/User Message:
DBMS/Debug Message:
Is there a way to check the domain first before attempting to send the email? I have a feeling I could also handle this on the SMTP server end by squelching this error, but I like the idea of being able to test an email domain first before sending it. Thanks for your ideas!
Here is the pertinent code just for reference (variables are filtered in from a form):
$headers['To'] = $to_address;
$headers['From'] = $from;
$headers['Reply-To'] = $from;
$headers['Subject'] = $subject;
$this->setHTMLBody($body);
$body = $this->get(array('text_charset' => 'utf-8'));
$headers = $this->headers($headers, true);
$message =& Mail::factory('smtp');
$mail = $message->send($to_address,$headers,$body);
You could use Net_DNS2 to determine if the domain exists and if so, send the email on it's merry way.
include "Net/DNS2.php";
$r = new Net_DNS2_Resolver();
try {
$result = $r->query($domain, 'MX');
} catch(Net_DNS2_Exception $e) {
$result = null;
}
if ($result !== null) {
// send email...
}
Naturally, I'd suggest some level of caching so you aren't repeating lookups.

PHP Twilio App - Including SMS file breaks Foreach loop

I cant figure this out so I'm hoping you can lend a hand.
I am creating a twilio app, and I'm including this entire file in a foreach loop. But it keeps breaking my loop and wont continue after it runs.
It works great, but the foreach this is included inside of will not continue after it runs.
Any ideas?
Thanks,
Nick
<?php
//shorten the URL
$tinyurl = file_get_contents("http://tinyurl.com/api-create.php?url=".$ebay_url);
// Include the PHP TwilioRest library
require "twilio/twilio.php";
// Twilio REST API version
$ApiVersion = "2010-04-01";
// Set our AccountSid and AuthToken
$AccountSid = "removed";
$AuthToken = "removed";
// Instantiate a new Twilio Rest Client
$client = new TwilioRestClient($AccountSid, $AuthToken);
// make an associative array of server admins
$people = array(
"removed"=>"Nick",
//"4158675310"=>"Helen",
//"4158675311"=>"Virgil",
);
// Iterate over all our server admins
foreach ($people as $number => $name) {
// Send a new outgoinging SMS by POST'ing to the SMS resource */
// YYY-YYY-YYYY must be a Twilio validated phone number
$response = $client->request("/$ApiVersion/Accounts/$AccountSid/SMS/Messages",
"POST", array(
"To" => $number,
"From" => 'removed',
"Body" => 'Alert! '.$title.' found for '. $price. '. View the item here: '.$tinyurl,
));
if($response->IsError)
echo "Error: {$response->ErrorMessage}\n";
else
echo "Sent message to: {$response->ResponseXml->SMSMessage->To}\n";
}
?>
I think the problem is that you're doing a require inside the for loop. There are objects defined in that twilio library so the second time you require it, the classes get defined again and this throws an error.
If you have error_reporting(E_ALL) set then you'll see an exception to that effect in your output.
I would either change it to a require_once or move it out of the for loop.
I hope that helps.

problem sending email with attachment

I'm new to using EWS from Exchangeclient classes.
I'm looking for a simple example how to send an email with an attachment. I've found examples about how to send an email but not sending an email with an attachment.
This is my script:
$exchangeclient = new Exchangeclient();
$exchangeclient->init($username, $password, NULL, 'ews/Services.wsdl');
$exchangeclient->send_message($mail_from, $subject, $body, 'HTML', true, true);
I have the following soap request.
$CreateItem->MessageDisposition = "SendAndSaveCopy";
$CreateItem->SavedItemFolderId->DistinguishedFolderId->Id = "sentitems";
$CreateItem->Items->Message->ItemClass = "IPM.Note";
$CreateItem->Items->Message->Subject = $subject;
$CreateItem->Items->Message->Body->BodyType = $bodytype;
$CreateItem->Items->Message->Body->_ = $content;
$CreateItem->Items->Message->ToRecipients->Mailbox->EmailAddress = $to;
$CreateItem->Items->Message->Attachments->FileAttachment->AttachmentId = $attach['AttachmentId'];
$CreateItem->Items->Message->Attachments->FileAttachment->Name = $attach['Name'];
$CreateItem->Items->Message->Attachments->FileAttachment->ContentType = $attach['ContentType'];
$CreateItem->Items->Message->Attachments->FileAttachment->ContentId = $attach['AttachmentId'];
$CreateItem->Items->Message->Attachments->FileAttachment->Content = $attach['ContentId'];
$CreateItem->Items->Message->Attachments->FileAttachment->Size = $attach['Size'];
The error I am getting is:
Fatal error: Uncaught SoapFault exception: [a:ErrorSchemaValidation] The request failed schema validation: The required attribute 'Id' is missing.
In order to send email with an attachment you have to first create the Message (Item) without any recipients (and a MessageDisposition of "SendToNone" or something like that) and save it in your Drafts folder. THEN create a request for a CreateAttachment, like so, where $key is the changekey of the item you created earlier (you have to read back the server response and save the changekey somewhere, because the changekey changes for an item with every modification it undergoes):
$attachrequest->ParentItemId->ChangeKey = $key;
$attachrequest->Attachments->FileAttachment->Name = $attachment_name;
$attachrequest->Attachments->FileAttachment->ContentLocation = $attachment;
$attachrequest->Attachments->FileAttachment->Content = $attachment_content;
$attachrequest->Attachments->FileAttachment->ContentType = $attachment_contenttype;
$response = self::$ews->CreateAttachment($attachrequest);
THEN you update the message (with an UpdateItem) to include recipients and so that the MessageDisposition is something like SendToAllAndSaveCopy.
(Disclaimer: I'm using this method now and it's all working fine, except for identifying the right format for Attachments->FileAttachment->Content, which looks like it should be the encoded base64 data of the attachment--but my computer can't open the attachments I'm sending.)
At any rate I believe this is the way to do it, and certainly I have been able to send messages with attachments with it.

Categories