Showing posts with label PHP. Show all posts
Showing posts with label PHP. Show all posts

Saturday, October 18, 2014

PHP SMTP GoDaddy Email Alternative: SendGrid

If you have ever worked with GoDaddy's SMTP relay email service, you will find it sometimes just quits working. I know GoDaddy is not about being a reliable company known for quality so it very silly of me to complain. However, I kind of need to send out emails from a website as needed, NOT just when GoDaddy thinks it is needed.
I finally was fed up with this terrible service. And Gmail, which I was trying to use as an alternative, just up and deleted my email account for whatever reason, so I searched out an alternative. I found SendGrid. For a basic 'FREE' account, I can send up to 200 emails per day. Which is definitely good enough for me - I am not sending spam, I am sending out an occasional newsletter to a subscribed membership!
For PHP, you need at least 5.3, I believe. You can download their code package to use or replace your SMTP credentials.
Here is a sample using their code package:
  1. include('sendgrid-php/sendgrid-php.php');
  2. function sendEmailSendGrid($subject, $message, $to, $fileName){
  3.         
  4.      $sendgrid = new SendGrid('myusername', 'mypassword');
  5.      $to = trim($to);
  6.      $htmlMessage = "<html><body>".$message."</body></html>";
  7.      $from='junk@junk.com';
  8.     
  9.      $email = new SendGrid\Email();
  10.      $email->addTo($to)->
  11. setFrom($from)->
  12. setSubject($subject)->
  13. setText($message)->
  14. setHtml($htmlMessage);
  15. if($fileName != "")
  16.     $email->addAttachment($fileName);
  17.     
  18. return $sendgrid->send($email);
  19.     
  20. }
Otherwise replace your SMTP stuff like this:
  1. function sendEmailSendGrid($subject, $message, $to, $rid, $nid){
  2.     
  3.      $to = trim($to);
  4.     
  5.      $htmlMessage = "<html><body>".$message."</body></html>";
  6.     
  7.      $host = "smtp.sendgrid.net";
  8. $port = "587";
  9. $username = "username";
  10. $password = "password";
  11. $crlf = "\n";
  12.     
  13. $smtp = Mail::factory('smtp',
  14. array ('host' => $host,
  15. 'port' => $port,
  16. 'auth' => true,
  17. 'username' => $username,
  18. 'password' => $password));
  19.         
  20.     $from='junk@junk.com';
  21.                  
  22. $headers = array ('From' => $from,
  23. 'To' => $to,
  24. 'Subject' => $subject,
  25. 'Content-type' => 'text/html; charset=iso-8859-1');
  26. $mail = $smtp->send($to, $headers, $htmlMessage);
  27. if (PEAR::isError($mail)) {
  28. echo("<p>" . $mail->getMessage() . "</p>");
  29. } else {
  30. echo("<p>Message successfully sent to: ".$to."</p>");
  31. }
  32. }

Tuesday, August 7, 2012

Picup App load image locally rather than using Imgur

A few months back I blogged about using the Picup app to grap iPhone/iPod/iPad pictures from their "i"-device to your website.

The part that has been bugging me was doing a remote upload to Imgur rather than a local upload to my server. I assume Imgur owns any image you upload to them which was a concern of mine.

So I spent some time yesterday trying to figure out my missing piece. I was relieved when I figured out that it was not my lack of brain power :) but rather the technology that I was using. I don't generally use classic ASP. I prefer ASP.NET/C# or PHP any day! With Classic ASP, you cannot easily upload files to your server by accessing the response.form. Instead, you have to download one of several 3rd party components to get the files, which then you have to register the dll blah blah blah.

However, on my server I happened to also have access to PHP. Out of frustration, I thought I will just try all my code on PHP to see if the upload will work. And it did...easily.

So to re-iterate the steps:

STEP 1. Create initial page with an input button, here is a short sample:
<html>
<header></header>
<body class="iphone" onLoad="loadMobile();" >
<form method="post" name="form1">

<input type="file" name="attach1" id="attach1"/>

</body></form></html>
STEP 2. Add script calls to that page.
<script type="text/javascript" src="js/picup.js"></script>
<script type="text/javascript" src="js/prototype.js"></script>
STEP 3. Add javascript function that sets up picup app settings. This function is loaded on the body "onLoad" see step 1. You could probably use jQuery to load this after document ready...
<SCRIPT TYPE="text/javascript">
function loadMobile(){

Picup.checkHash();
var url = escape('http://yourwebsite.com/uploadPhoto.asp');
var posturl = escape('http://yourwebsite.com/get-posted.php');

currentParams = {
'callbackURL': url, //the page called after upload.
'referrername'   : escape('mywebsitename'),
'referrerfavicon'  : escape('http://yourwebsite.com/images/favicon.ico'),
'purpose'               : escape('Select...message to user..'),
'debug'   : 'false',
'returnThumbnailDataURL': 'false',
'thumbnailSize'         : '80',
'postURL': posturl,    //the page that will upload the photo
'returnServerResponse':'true' //returns output of posturl
};

Picup.convertFileInput($('attach1'), currentParams);
}
</script>
STEP 4. Setup the "postURL" page, for me it is a simple PHP file. It outputs the name of the file as the response body so that my callback page can get the file name and update records accordingly.
<?php
if (isset($_FILES)){
 foreach ($_FILES as $key => $file){
  move_uploaded_file($file['tmp_name'], 'photos/'.$file['name']);
  echo $file['name'];
 }
}
?>
STEP 5. Setup the javascript on the callback page to grab the file name...and anything else that it needs.
<SCRIPT TYPE="text/javascript">
var fileName = unescape(getHashUrlVars()['serverResponse']);
var success = getHashUrlVars()['status'];

//parse hashed values from url
function getHashUrlVars(){
 var vars = [], hash;
 var hashes = window.location.href.slice(window.location.href.indexOf('#') + 1).split('&');
 for(var i = 0; i < hashes.length; i++)
 {
 hash = hashes[i].split('=');
 vars.push(hash[0]);
 vars[hash[0]] = hash[1];
 }
 return vars;
}

....process as needed

I hope this helps.

Sunday, November 13, 2011

PHP PEAR Spreadsheet

I had my PHP/PEAR Spreadsheet writing working for several months on GoDaddy, however, GoDaddy did an upgrade of Apache to 1.3.33 without me knowing. So I found out a month later that my spreadsheet writer was no longer working. I found that the OLE was erroring out that is could not create a temp file.(after days of debugging).

To fix this error, I added a temp directory to the code like this:

$excel = new Spreadsheet_Excel_Writer($name);

//needed for upgrade to apache 1.3
$excel->setTempDir('temp');


Of course, I added the folder to the server, and it is working...after days and days of head-banging....

Sunday, August 14, 2011

PHP Pear Spreadsheet Write - File Error: Data may have been lost

I needed to write out data to a spreadsheet file so I installed PHP PEAR's Spreadsheet Excel Writer. It is pretty easy to use. I wrote the code I needed but kept getting the following error upon opening the file:
File Error: Data may have been lost.

So then I went to PHPExcel, however, when I installed the code to production I realized it was still on PHP4, and that only works with PHP5...

So I went back to the Spreadsheet Excel Writer. I noticed that the files opened just fine, and all the data was there, so it really worked, however, I imagined fielding calls from user's asking what the error was...and I felt it would be more credible if I did not have this error popping up.

So along the way I figured out what caused the error for myself. I had several 'for loops' that wrote out data like this:

foreach ($collection as $key => $value)
{
$value = trim($value);

if($value != "")
$sheet->write($index,$cellLetter, $value);

}

So I replaced the 'for loops' with the 'writeCol' function that would write out an entire collection into a column.

$sheet->writeCol (8 , 3 , $collection);

This worked for almost every instance where I was looping thru collections, there was one instance where I could not apply this logic, but since it was only about 10 lines of repeating code, I opted to do that rather than cause the Data Lost error. So I am pretty happy with that.

If we ever upgrade to PHP5, I will consider just using the PHPExcel code since I never had the Data Lost error with it.

Hope that helps!

Saturday, July 9, 2011

Struggling with PHP SMTP/Email?

Well, as I am diving into the world of PHP (coming from a Microsoft world), I have found setting up the PHP environment to be rather frustrating for myself. With MS, you install Visual Studio, use the built in web server or optionally hook up to the local IIS and you're off for the most part.

However, PHP, in my experience, isn't so ready to go. The installation of extra stuff can be quite a headache, but it is open source/free so you learn to just deal with it I suppose.

So I wanted to get a small program to send email. From my reading, I needed to install PEAR. I found this article to be the most helpful, easy instructions for those on a Windows system. http://www.geeksengine.com/article/install-pear-on-windows.html

I later found I needed to two more installs the Net_SMTP and the Net_Socket, it said Net_SMTP is optional, but I think I needed it.

To install these, I follow the same idea, I download the archive file, then unzip it to a local folder, copy the needed file/folder located inside to the PEAR directory which is inside the PHP install directory.

Extra installs:

http://pear.php.net/package/Net_SMTP/

http://pear.php.net/package/Net_Socket/

For the Net_SMTP, I copied SMTP.php to the NET folder (you many need to create the NET folder)

And then for the Net_Socket, I copied the Socket.php to the NET folder.

I can't quite be sure this are the precise/correct instructions, but I do know I was able to successfully send email!