Amazon SES + PHP - php

I'm trying to set up amazon SES with PHP. I've scoured the internet and the documentation for AWS PHP SDK but I only see outdated scripts on how to include the actual library and send e-mail. Does anyone here have a working script for using Amazon SES with PHP?
This is the closest I've found to test the script but it doesn't work:
require 'src/aws.phar';
use Aws\Common\Enum\Region;
use Aws\Ses\SesClient;
try {
$ses = SesClient::factory(array(
'key' => 'AKIAJ4ERVU6XXXXXXX',
'secret' => 'kMgagzJmB4Xjw7UD+Md0KNgW+CTE2jCXXXXX/',
'region' => Region::US_EAST_1
));
$ses->verifyEmailIdentity( array(
'EmailAddress' => 'jason#aol.com'
));
}
catch( Exception $e )
{
echo $e->getMessage();
}

First, you would want to disable/delete and generate new keypairs so that you would not have to face bad situation as there are scrapers/bots and people who might misuse your access key-pairs.
As for your original question, you didn't describe what didn't work for you. Anyway, since you wanted a working version, check the source code of this: https://github.com/daniel-zahariev/php-aws-ses which will give you enough idea to get yours working.

This is the working code that i got for you, let me know if this helps
<?php
require 'aws.phar';
use Aws\Ses\SesClient;
$client = SesClient::factory(array('region'=>'us-east-1','version'=>
'latest','credentials' => array('key' => 'xxxxx','secret' => 'xxxxxx',)));
$msg = array();
$msg['Source'] = $message['from'];
$msg['Destination']['ToAddresses'][] = $to_address;
$msg['ReplyToAddresses'][] = $from;
$msg['Message']['Subject']['Data'] = $subject;
$msg['Message']['Subject']['Charset'] = "UTF-8";
$msg['Message']['Body']['Html']['Data'] = $body;
$msg['Message']['Body']['Html']['Charset'] = "UTF-8";
try{
$result = $client->sendEmail($msg);
$logmsg = "Passed ".from." - ".to_address;
} catch (Exception $e) {
$logmsg = "Failed ".$message['from']." - ".$to_address;
error_log('Failed Email '.from." - ".$to_address);
}

Related

How do I set transactional email attributes in Sendinblue api v3?

So, I'm novice at best with php, but I've figured out how to set up and send transactional emails with sendinblue.
But for whatever reason, I can't seem to set the attributes.
This is really the only line of the code that I can't seem to get to work.
$sendEmail['attributes'] = array('FIRSTNAME' => "STEVE");$sendEmail['attributes'] = array('FIRSTNAME' => "STEVE");
I've also tried
$sendEmail['params'] = array('FIRSTNAME' => "STEVE");
and
$params['attributes'] = array('FIRSTNAME' => "STEVE");
...and probably 127 variations of the above, but I can't seem to get it it to work.
I also can't seem to figure out how to create a contact with php...
What is the "create contact" equivilent of this line of code:
$sendEmail = new \SendinBlue\Client\Model\SendEmail();
?
Like I said, my emails asre sending, but where I expect them to read "Dear STEVE," they read "Dear ,"
BELOW IS THE FULL CODE:
<?php
# Include the SendinBlue library\
require_once('../vendor/autoload.php');
# Instantiate the client\
$config = SendinBlue\Client\Configuration::getDefaultConfiguration()->setApiKey('api-key', 'MY API KEY HERE');
// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
// $config = SendinBlue\Client\Configuration::getDefaultConfiguration()->setApiKeyPrefix('api-key', 'Bearer');
// Configure API key authorization: partner-key
$config = SendinBlue\Client\Configuration::getDefaultConfiguration()->setApiKey('partner-key', 'MY API KEY HERE');
// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
// $config = SendinBlue\Client\Configuration::getDefaultConfiguration()->setApiKeyPrefix('partner-key', 'Bearer');
$apiInstance = new SendinBlue\Client\Api\SMTPApi(
// If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`.
// This is optional, `GuzzleHttp\Client` will be used as default.
new GuzzleHttp\Client(),
$config
);
$templateId = 2; // int | Id of the template
$sendEmail = new \SendinBlue\Client\Model\SendEmail(); // \SendinBlue\Client\Model\SendEmail |
$sendEmail['emailTo'] = array("test#example.com");
$params['attributes'] = array('FIRSTNAME' => "STEVE"); //THIS IS THE LINE OF CODE THAT ISN'T WORKING.
//$mail->setFrom('info#myeasy.wedding', 'My Easy Wedding');
try {
$result = $apiInstance->sendTemplate($templateId, $sendEmail);
print_r($result);
} catch (Exception $e) {
echo 'Exception when calling SMTPApi->sendTemplate: ', $e->getMessage(), PHP_EOL;
}
?>
You need to use sendTransacEmail() and it works with PARAM. Need to add code in template {{ params.FIRSTNAME }}
Complete API code
$config = SendinBlue\Client\Configuration::getDefaultConfiguration()->setApiKey('api-key', 'MY API KEY HERE');
$apiInstance = new SendinBlue\Client\Api\TransactionalEmailsApi(
// If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`.
// This is optional, `GuzzleHttp\Client` will be used as default.
new GuzzleHttp\Client(),
$config
);
$sendEmail = new SendinBlue\Client\Model\SendSmtpEmail();
$sendEmail['to'] = [["email" => 'test#example.com', "name" => 'test']];
$sendEmail['templateId'] = 2;
$sendEmail['params'] = ['FIRSTNAME' => 'Test'];
try {
$response = $apiInstance->sendTransacEmail($sendEmail);
print_r($response);
} catch (Exception $e) {
echo 'Exception when calling AccountApi->getAccount: ', $e->getMessage(), PHP_EOL;
}
try to use FNAME instead of FIRSTNAME
Reference
<?php
require_once(__DIR__ . '/vendor/autoload.php');
$config = SendinBlue\Client\Configuration::getDefaultConfiguration()->setApiKey('api-key', 'YOUR API KEY');
$apiInstance = new SendinBlue\Client\Api\TransactionalEmailsApi(
new GuzzleHttp\Client(),
$config
);
$templateId = 1;
$sendEmail = new \SendinBlue\Client\Model\SendEmail()
$sendEmail['emailTo'] = array('example#example.com');
$sendEmail['emailCc'] = array('example1#example1.com');
$sendEmail['headers'] = array('Some-Custom-Name' => 'unique-id-1234');
$sendEmail['attributes'] = array('FNAME' => 'Jane', 'LNAME' => 'Doe');
$sendEmail['replyTo'] = 'replyto#domain.com';
$sendEmail['attachmentUrl'] = 'https://example.net/upload-file.pdf';
try {
$result = $apiInstance->sendTemplate($templateId, $sendEmail);
print_r($result);
} catch (Exception $e) {
echo 'Exception when calling TransactionalEmailsApi->sendTemplate: ', $e->getMessage(), PHP_EOL;
}
?>
You can find more examples at https://developers.sendinblue.com/

php-mailparse composer not loading on server

I have an Ubuntu php7.0 server and I am trying to use a php Mailparse script I found here
However I confirmed that composer is installed on the server and mailparse is also on the server. However the below script returns a 500 error and I tracked it down to the top two lines of code that is causing it and not sure how to resolve it.
So what I mean is when I comment out the two lines that say
require_once __DIR__.'/vendor/autoload.php';
$Parser = new PhpMimeMailParser\Parser();
Then the script will load but of course the mail parse wont work??
//load the php mime parse library
require_once __DIR__.'/vendor/autoload.php';
$Parser = new PhpMimeMailParser\Parser();
//Include the AWS SDK using the Composer autoloader.
require 'awssdk/aws-autoloader.php';
use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;
// AWS Info
$bucketName = 'pipedemail';
$IAM_KEY = '******';
$IAM_SECRET = '******';
// Connect to AWS
try {
// You may need to change the region. It will say in the URL when the bucket is open
// and on creation. us-east-2 is Ohio, us-east-1 is North Virgina
$s3 = S3Client::factory(
array(
'credentials' => array(
'key' => $IAM_KEY,
'secret' => $IAM_SECRET
),
'version' => 'latest',
'region' => 'us-east-1'
)
);
} catch (Exception $e) {
// We use a die, so if this fails. It stops here. Typically this is a REST call so this would
// return a json object.
die("Error: " . $e->getMessage());
}
// Use the high-level iterators (returns ALL of your objects).
$objects = $s3->getIterator('ListObjects', array('Bucket' => $bucketName));
foreach ($objects as $object)
{
$objectkey = $object['Key'];
$path = "https://s3.amazonaws.com/pipedemail/$objectkey";
//lets get the raw email file to parse it
$Parser->setText(file_get_contents($path));
// Once we've indicated where to find the mail, we can parse out the data
$to = $Parser->getHeader('to'); // "test" <test#example.com>, "test2" <test2#example.com>
$addressesTo = $Parser->getAddresses('to'); //Return an array : [[test, test#example.com, false],[test2, test2#example.com, false]]
$from = $Parser->getHeader('from'); // "test" <test#example.com>
$addressesFrom = $Parser->getAddresses('from'); //Return an array : test, test#example.com, false
$subject = $Parser->getHeader('subject');
}

twilio catching error does not work

I am implementing twilio in my laravel 5 application. To use it in the framework I use aloha/laravel-twilio integration.
Sending a valid request with test-credentials works fine. I have problems when I want to implement an error-handling.
For some reason the catch does not get the error, which results in a crash of the app. The error seems to be in the twilio-sdk if I read the error message correctly.
Here is what I've done so far:
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
use Aloha\Twilio\TwilioInterface;
class Activation extends Model {
protected $fillable = array( 'a', 'b', 'c');
public static function send() {
// Testaccount
// $toNumber = '+15005550006'; // valid number; works fine
$toNumber = '+15005550001'; // #todo will throw an exeption, and breaks the app
try {
\Twilio::message( $toNumber, 'Pink Elephants and Happy Rainbows');
} catch ( Services_Twilio_RestException $e ) {
elog( 'EACT', $e->getMessage( ) , __FUNCTION__ ); // this is not called when an twilio error occurs
}
}
}
This results in the following error:
Whoops, looks like something went wrong.
Services_Twilio_RestException in /path/to/my/laravel/vendor/twilio/sdk/Services/Twilio.php line 297
Exception_message: The 'To' number +15005550001 is not a valid phone number.
From the documentation this error (not valid phone numer) shall be thrown, but I should have a possiblity to catch and process it. Currently, this does not work. I do not get the error catched...
How can I get the twilio-errors catched and processed?
The class is in a namespace, so I have to reference the absolut class exception - \Services_Twilio_RestException - in the catch .
It works with this code:
try {
\Twilio::message( $toNumber, 'Pink Elephants and Happy Rainbows');
} catch ( \Services_Twilio_RestException $e ) {
elog( 'EACT', $e->getMessage( ) , __FUNCTION__ );
}
See below which is valid as of today. TwilioException is not valid and neither is Services_Twilio_RestException. You should use Exception instead.
UPDATE
You need to import Twilio\Exceptions\TwilioException for TwilioException to work.
My use case is I had to send to a database of numbers and not have an invalid phone number break my script. We did some work-around a month or two ago which involved logging when a message was sent and had a cron job checking where we left off every two minutes... not efficient when you're sending tens of thousands of text messages.
require_once '../Twilio/autoload.php'; // Loads the library
use Twilio\Rest\Client;
//some test fail numbers
$arr = array(1234567890,"11855976lend1",321619819815,198198195616516);
/* ==================================================================================
//create a function to send SMS using copilot (uses an SID instead of a phone number)
================================================================================*/
function sendSMS($to){
// Download the PHP helper library from twilio.com/docs/php/install
// These vars are your accountSid and authToken from twilio.com/user/account
$account_sid = 'xxx';
$auth_token = 'xxx';
$client = new Client($account_sid, $auth_token);
//this nifty little try/catch will save us pain when we encounter bad phone numbers
try{
$client->messages->create(
$to,
array(
'messagingServiceSid' => "MGxxx",
'body' => "This is the body we're sending."
)
);
//sent successfully
echo "sent to $to successfully<br>";
}catch(Exception $e){
echo $e->getCode() . ' : ' . $e->getMessage()."<br>";
}
}
foreach($arr as &$value){
sendSMS($value);
}
//remember to unset the pointer so you don't run into issues if re-using
unset($value);
Today (19-May-2017) the code is like this :
// Step 1: set our AccountSid and AuthToken from https://twilio.com/console
$AccountSid = "XXX";
$AuthToken = "XXX";
$client = new Client($AccountSid, $AuthToken);
try {
$sms = $client->account->messages->create(
// the number we are sending to - Any phone number
$number,
array(
// Step 2: Change the 'From' number below to be a valid Twilio number
// that you've purchased
'from' => "+XXXXXXXXXXX",
// the sms body
'body' => $sms
)
);
// Display a confirmation message on the screen
echo "Sent message to $name";
} catch (TwilioException $e) {
die( $e->getCode() . ' : ' . $e->getMessage() );
}
This is what worked for me:
$twilioCli = new \Twilio\Rest\Client(config('app.twilioAccountSID'), config('app.twilioAuthToken'));
try {
$twilioCli->messages->create(
$formattedToNum,
[
'from' => config('app.twilioFromNumber'),
'body' => "sms body goes here"
]
);
}
catch (\Twilio\Exceptions\RestException $e) {
echo "Error sending SMS: ".$e->getCode() . ' : ' . $e->getMessage()."\n";
}

Twitter APIs not working on hosting [Works fine on localhost]

I am working on an app to show the tweets done in 1 mile radius of given geolocation (Latitude and Longitude). This is my PHP code,
<?php
// $lat = $_GET['lat'];
$lat = 26.511740;
// $long = $_GET['long'];
$long = 80.234973;
require_once("twitteroauth/twitteroauth.php"); //Path to twitteroauth library
$notweets = 100;
$consumerkey = "XXXX";
$consumersecret = "XXXX";
$accesstoken = "XXXX-XXXX";
$accesstokensecret = "XXXX";
function getConnectionWithAccessToken($cons_key, $cons_secret, $oauth_token, $oauth_token_secret) {
$connection = new TwitterOAuth($cons_key, $cons_secret, $oauth_token, $oauth_token_secret);
return $connection;
}
$connection = getConnectionWithAccessToken($consumerkey,$consumersecret, $accesstoken, $accesstokensecret);
$tweets = $connection->get("https://api.twitter.com/1.1/search/tweets.json?geocode=".$lat.",".$long.",5mi&result_type=recent&count=".$notweets);
// echo $tweets;
echo json_encode($tweets);
?>
I am using Wamp server (PHP V5.5.12) and my code is working fine on it. But when I host my application on some free hosting sites (I have tried hostinger.in and 000webhost.com), this script fails and just prints 'null'.
Please help me to solve this problem.
Thanks in advance.
I've tried in both, hostinger and 000webhost and several others. The reason they dont work is the library to connect to twitter uses php curl, and many free hosting have disabled curl, or outgoing connections or twitter refuses the curl connection when it comes from the ips from free hosting servers. For what I've read in internet it's probably because many hackers have been messing with twitter and hosting from free hosting accounts. So finding a free hosting with cpanel that works with Twitter API it's a challenge, i've tried over 20 and they dont work, some of them automatically deleted the account or the file or block the ftp access if you try to curl to twitter
Likely to be related to the libraries available to you.
Add error_reporting(E_ALL) to the top of the script.
Check that cURL is installed on the cheap hosting as I believe that's the only php library that twitteroauth requires.
What is your TwitterOAuth version? Your code seems to be so legacy and not compatible with latest version.
https://twitteroauth.com/
<?php
require "vendor/autoload.php";
use Abraham\TwitterOAuth\TwitterOAuth;
$lat = 26.511740;
$long = 80.234973;
$notweets = 100;
$ck = "XXXX";
$cs = "XXXX";
$ot = "XXXX-XXXX";
$os = "XXXX";
$to = new TwitterOAuth($ck, $cs, $ot, $os);
$tweets = $to->get('search/tweets', [
'geocode' => "$lat,$long",
'result_type' => 'recent',
'count' => $notweets,
]);
if (isset($tweets->errors[0]->message)) {
echo 'Error: ' . $tweets->errors[0]->message;
} elseif (!is_array($tweets)) {
echo 'Unknown Error';
} else {
echo '<pre>';
var_dump($tweets);
echo '</pre>';
}
Alternatively, you can use TwistOAuth instead of TwitterOAuth. I'm the author of this library. This library is almost compabible with TwitterOAuth, but support strict exception handling. Error reasons are always to be clear.
https://github.com/mpyw/TwistOAuth
<?php
require 'TwistOAuth.phar'; // Or 'vendor/autoload.php' for composer
$lat = 26.511740;
$long = 80.234973;
$notweets = 100;
$ck = "XXXX";
$cs = "XXXX";
$ot = "XXXX-XXXX";
$os = "XXXX";
try {
$to = new TwistOAuth($ck, $cs, $ot, $os);
$tweets = $to->get('search/tweets', [
'geocode' => "$lat,$long",
'result_type' => 'recent',
'count' => $notweets,
]);
echo '<pre>';
var_dump($tweets);
echo '</pre>';
} catch (TwistException $e) {
echo 'Error: ' . $e->getMessage();
}
Which code do you like?

Upload to YouTube using Zend - via a proxy

I've been successfully uploading videos to YouTube using some code I found (Zend with YouTube API).
I modified it so that I can upload via a proxy server, but I've hit a brick wall. I've commented which lines I added to implement the proxy support. Here is the code:
<?php
require_once 'Zend/Loader.php';
Zend_Loader::loadClass('Zend_Gdata');
Zend_Loader::loadClass('Zend_Gdata_YouTube');
Zend_Loader::loadClass('Zend_Gdata_AuthSub');
Zend_Loader::loadClass('Zend_Gdata_ClientLogin');
Zend_Loader::loadClass('Zend_Http_Client_Exception'); //added for proxy support
Zend_Loader::loadClass('Zend_Http_Client'); //added for proxy support
Zend_Loader::loadClass('Zend_Http_Client_Adapter_Proxy'); //added for proxy support
Zend_Loader::loadClass('Zend_Gdata_App_HttpException'); //added for proxy support
$config = array(
'adapter' => 'Zend_Http_Client_Adapter_Proxy',
'proxy_host' => 'MY_PROXY_IP',
'proxy_port' => 8080,
'proxy_user' => 'USER',
'proxy_pass' => 'PASS'
); //added for proxy support
$proxiedHttpClient = new Zend_Gdata_HttpClient('http://www.google.com/', $config); //added for proxy support
try
{
$authenticationURL= 'https://www.google.com/accounts/ClientLogin';
$httpClient = Zend_Gdata_ClientLogin::getHttpClient(
$username = 'YOUTUBE EMAIL ID',
$password = 'YOUTUBE PASSWORD',
$service = 'youtube',
$client = $proxiedHttpClient, //changed from "$client = null"
$source = 'mysource',
$loginToken = null,
$loginCaptcha = null,
$authenticationURL);
}
catch (Zend_Gdata_App_Exception $e)
{
$arry['data']['flag'] = false;
$arry['data']['msg'] = 'Username or Password Invalid.';
print_r(json_encode($arry));
die();
}
$httpClient->setConfig($config); //added for proxy support
$developerKey='DEVELOPER KEY';
$applicationId = 'not require';
$clientId = 'not require';
$yt = new Zend_Gdata_YouTube($httpClient, $applicationId, $clientId, $developerKey);
$fileName = "FILENAME";
$fileType = "video/mp4";
$newEntry = new Zend_Gdata_YouTube_VideoEntry();
$filesource = $yt->newMediaFileSource($fileName);
$filesource->setContentType('video/mp4');
$filesource->setSlug($fileName);
$newEntry->setMediaSource($filesource);
$newEntry->setVideoTitle("VIDEO TITLE");
$newEntry->setVideoDescription("VIDEO DESCRIPTION HERE");
$newEntry->setVideoCategory("VIDEO CATEGORY HERE");
$newEntry->setVideoTags("VIDEO TAGS");
try {
$newEntry = $yt->insertEntry($newEntry, 'http://uploads.gdata.youtube.com/feeds/api/users/default/uploads', 'Zend_Gdata_YouTube_VideoEntry');
$state = $newEntry->getVideoState();
if ($state)
{
$videourl = $newEntry->getVideoWatchPageUrl();
$arry['data']['flag'] = true;
$arry['data']['url'] = $videourl;
$arry['data']['msg'] = "Video Uploaded Successfully.";
}
else
{
$arry['data']['flag'] = false;
$arry['data']['msg'] = "Not able to retrieve the video status information yet. " ."Please try again later.\n";
}
}
catch (Zend_Gdata_App_Exception $e) {
$arry['data']['flag'] = false;
$arry['data']['msg'] = $e->getMessage();
}
echo "<pre>";
print_r($arry);
?>
When I execute the PHP from the command line, the message it gives back is:
Trying to write but we are connected to the wrong proxy server
The proxies I've been testing with definitely work - in fact, if I use a broken proxy it just says "Username or Password is invalid." I only get the error message above when using working proxies.
Any guidance or solution would be greatly appreciated.
I had the same problem and I found a solution that worked for me. I used the built in cURL Adapter instead of the Proxy adapter.
See my example below...
$config = array(
'adapter' => 'Zend_Http_Client_Adapter_Curl',
'curloptions' => array(CURLOPT_FOLLOWLOCATION => true, CURLOPT_PROXY => "proxy:port", CURLOPT_PROXYUSERPWD => "username:password")
);
This code is using turned down GData API and deprecated clientlogin
Please update to v3 API, here are PHP examples to get you started.

Categories