Send email using Gmail from PHP with ‘fsockopen’

21 Apr, 2013
Updated
22 Dec, 2012
Created

There are loads of wordpress plugins available which will help to to implement a contact form using gmail or other similar smtp hosts. But what if you want to have a custom functionality that requires you to send email from your blog.

While setting up this blog, I faced the problem of getting my contact form working with my gmail account. The theme that I am using, uses the PHP mail function to send emails. The problem with the inbuilt PHP mail function is that it doesn’t have any SMTP authentication mechanism. Moreover most of the email providers use SSL/TLS for connecting to the smtp server which is not supported in PHP mail.

Well, here’s a simple solution that allows you to send email using gmail without the need for any special permissions from you hosting provider.

Tesing your Server

First you need to check if your host supports SSL or TLS to send emails. To do this, create a new file in your webroot directory with a .php extension (e.g. smtp-test.php) so that you can access it via a url from your browser. Paste the following code in that file and save it.

The above code would allow you to check your hosting provider’s PHP capabilities and firewall settings. Try hitting the link from your browser. If you get SUCCESS, you can have the below solution implemented to send email using gmail.

The Code

I got the code from here which seemed to work perfectly. You can paste the following functions within any php file.

Usage

You can use the above functions to send emails as shown below.