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. }

No comments:

Post a Comment