Sending email with Gmail using the CodeIgniter PHP Framework

I have just implemented this functionality for OnePage and I’d like to share it in case people find it useful.
Why send email with Gmail rather than the server’s SMTP configuration?
There are a number of advantages I see for doing this:
  • Ability to develop locally and test email sending functionality without going to lengths to setup a local mail server.
  • Ability to utilise Google Apps emails to send email from emails which are on your own domain.
  • Ability to have a reference of the mail you send using this method in the “sent” folder on your Gmail account.
Right on!
So we’ve decided that’s the route we’re going to take, so lets get going! It’s rather simple actually, especially with the fantastic CodeIgniter framework and it’sEmail Class. It should work nicely for regular PHP or with other frameworks if you just take the concepts outlined here. I must also give credit to wrs from theCodeIgniter Forums, since it is his post which I have based my solution upon.
A new config file – email.php
Place the following code inside a new config file called “email.php” and put it in your application/config directory. Config files named with the same name as a library are included automatically, and this is what we’re doing here.
  1. <?php  if ( ! defined(‘BASEPATH’)) exit(‘No direct script access allowed’);
  2. /*
  3. | ——————————————————————-
  4. | EMAIL CONFING
  5. | ——————————————————————-
  6. | Configuration of outgoing mail server.
  7. | */
  8. $config[‘protocol’]=’smtp’;
  9. $config[‘smtp_host’]=’ssl://smtp.googlemail.com’;
  10. $config[‘smtp_port’]=’465′;
  11. $config[‘smtp_timeout’]=’30’;
  12. $config[‘smtp_user’]=’your gmail email’;
  13. $config[‘smtp_pass’]=’your gmail password’;
  14. $config[‘charset’]=’utf-8′;
  15. $config[‘newline’]=”\r\n”;
  16. /* End of file email.php */
  17. /* Location: ./system/application/config/email.php */
Make sure you change ‘your gmail email’ and ‘your gmail password’ appropriately.
Sending email, now sent through Gmail
Now any emails you send using the CodeIgniter Email Class will actually be sent from your Gmail account of choice:
  1. // send an email
  2. $this->load->library(’email’);
  3. $this->email->from(‘team@myonepage.com’,’Team OnePage’);
  4. $this->email->to(“something@someaddress.com”);
  5. $this->email->subject(‘A test email from CodeIgniter using Gmail’);
  6. $this->email->message(“I can now email from CodeIgniter using Gmail as my server!”);
  7. $this->email->send();
UPDATE: It seems Posterous thinks it’s clever by turning my email’s into links, even inside code. Please adjust your code accordingly 🙂
One drawback of this method
There is one drawback of this method, which is that you cannot specify the “from” email to be anything other than your Gmail email address or an email address you have associated with the Gmail account. All email will be sent from the email account you have setup as the default in your Gmail account.

Possible error – “Unable to find the socket transport “ssl” – did you forget to enable it when you configured PHP?”

If you got this error, like I did, then you need to enable SSL in your PHP config. Load up php.ini and find a line with the following:
;extension=php_openssl.dll
Simply remove the “;” and then restart Apache and you’re good to go. The “;” denotes that the line is a comment, and so removing it enables the SSL extension for Apache. Credit – http://www.boringguys.com/2007/07/20/unable-to-find-the-socket-transport-ssl-did-you-forget-to-enable-it-when-you-configured-php/
That’s all!
I hope that is useful for some people 🙂 I use it mainly for local development purposes – it’s nice to be able to test everything.
Personal notes:
Other error that you may find across:

Severity: Warning

Message: fsockopen() [function.fsockopen]: unable to connect to ssl://smtp.googlemail.com:465 (Connection timed out)

Filename: libraries/Email.php

–> Possible solution is to open port 465 (You may want to consult the issue to your web hosting provider)

Setting Up Google Apps (Gmail) For Your Domain

The other day, I was talking with my friend Aaron (@riddlebrothers) about all of the various e-mail addresses we have and how we use them. At one point, after discussing the virtues of using Yahoo! Mail, I mentioned that the e-mail addresses I have hosted on my own servers are often unreliable. I told him that I rarely give out anything but my Yahoo! e-mail address, because a lot of messages get lost in cyberspace with my other accounts.

He asked me if I had looked into using Google Apps for my domain-based e-mail services. I honestly hadn’t thought about it before (in fact, I made a post a while back about how strange it was that everyone was moving to Gmail). However, his suggestion made sense. Following are some of the advantages I see in moving your e-mail over to Google Apps:

  • Reliability – Although Gmail has been out of commission a few times over the last couple of months, it has proven to be reliable as an e-mail service. I rarely, if ever, hear about anyone losing e-mail messages or not receiving important messages when using Gmail.
  • Portability – How many times have you moved your domain to a new server and been frustrated by the fact that you lost all of your e-mail messages? If you switch over to Google Apps, you never have to worry about that again (at least, until Google goes away, which I don’t expect to happen any time soon). You can keep your e-mail on the same service even when you switch the server on which your Web site is hosted.
  • Service and support – Your e-mail service is important to you. If your e-mail is hosted on your Web server, and the e-mail service starts malfunctioning, you have little recourse but to contact your service provider. Nine times out of ten, the problem is relegated specifically to your server, and possibly even to your account. It makes it difficult to pinpoint the problem and fix it, and it means that you are probably not a high-priority. However, with Google, when a problem arises, it most likely effects everyone else that’s using Gmail, which means that fixing it becomes the highest priority for your service provider.
  • Server limits – Sure, when your e-mail service is hosted on your Web server, you generally get promises of outrageous amounts of storage space and unlimited e-mail accounts. However, as I pointed out in a previous post, most service providers actually limit the number of inodes on your account. Each e-mail message (sent, received, trash, etc.) counts as an individual inode. Therefore, if you have an account that limits you to 50,000 inodes, and you have 20,000 e-mail messages, you’ve already used up 40% of your inodes simply by having e-mail hosted on your server. You can eliminate that concern by moving your e-mail over to Google apps.

Moving Your Services to Google

Preparing for the Move

Before you actually start moving your e-mail services to the Google server, I would recommend backing up all of your old e-mail messages to a safe place. Once the migration is completed, it will be difficult (though not impossible) to access your old e-mail server using an e-mail client like Outlook.

In my case, I have created a new folder inside of my “On This Computer” folder in Evolution (in Outlook, I believe this is called “Local Folders”) for my Inbox and a new folder for my Sent messages. I then selected all of the messages in my Inbox on my current e-mail server and moved them into the new local folder I created. I repeated the same steps for my sent messages.

If you forget to take this step before you switch everything over, you might be able to access your old e-mail server using the IP address, depending on how your original e-mail server was configured. Evolution automatically chooses the appropriate port for the specific type of e-mail connection you’re using, so all I had to do was enter my IP address. However, if you are using an e-mail client that requires you to enter a port number, as well, I do know that secure (SSL) IMAP connections are usually on port 1096.

Creating Your Account

01-getting-startedNow that I’ve gone over the benefits of moving to Google Apps, I’m going to explain, step-by-step, how to accomplish this task. It’s actually very simple, but it will take a long time.

To begin with, head on over to Google and sign up for an account. For most of us, the free account offered by Google is more than enough. However, they do offer a “premier edition” if your needs exceed the services of the free accounts.

One important note: Although the comparison between the Standard Edition and the Premier Edition says that only the Premier Edition offers Microsoft Outlook interoperability, that does not mean you can’t use Microsoft Outlook (or the iPhone or any other e-mail client) with the Standard Edition. You can enable IMAP services on the Standard Edition and connect to it through Outlook. I am assuming that the “interoperability” to which they’re referring in that comparison is the automatic sync of e-mail, contacts and calendar all together, the way an Exchange server works.

02-domain-nameAnyway, go ahead and sign up for your account. For purposes of this article, I’m signing up for the Standard Edition. Just click the “Get Started” button and fill in the information requested.

  1. Indicate whether or not you own a domain name. If so, indicate whether or not you are an administrative user of the domain (do you have the ability to upload files via FTP or to modify the DNS entries). In my case, I am an administrator of the domain, so I have indicated that. Then, enter the domain name you will be using.
  2. 03-organization-informationFill in all of your contact information, information about your organization (if applicable) and make sure you agree to the fact that you have permission to edit your DNS entries. As with most Web forms, there are some required fields. In this particular instance, they are currently indicated with an asterisk (*) to the right of the label. If you don’t provide the required information, you will receive an error when you submit the form.
    Important: Make absolutely certain that you are able to edit your server’s DNS zone files before filling in this form. If you cannot edit your DNS zone files, do not proceed. Signing up for the Google Apps account is useless if you’re not going to be able to modify your server appropriately to have the e-mail go where it’s intended.
  3. 04-administrator-accountCreate your first e-mail account. This e-mail account will be used as the administrative account for the Google Apps services. If you are actually moving an existing e-mail service over to Google Apps, I would recommend using the same username you are already using for your e-mail. However, you can use any username you desire.
    In this step, you will be confronted with the Terms and Conditions. These terms and conditions are fairly standard for Google’s services, but they are worth a quick read. Keep in mind that these terms also include, by reference, the Google Privacy Policy and the Program Policy, so you might need to read those, as well.
    If you will be using your e-mail to send and receive highly confidential information, you really should read these terms carefully. You might even want to have a lawyer review them before proceeding. Google does sometimes have some abnormal terms relating to the ownership and usage of the data in your account, so this may not be the ideal solution if you are transmitting highly confidential or sensitive information.

Verify Domain Ownership

05-domain-verificationThe next step in the process is to prove to Google that you own and have administrative rights to the domain you chose. You have two options to prove you own the domain. The first option is to simply create and upload an HTML file to your Web server. This method of verification is similar to the way you verify ownership when setting up an Analytics account. The other option is to modify your DNS entries to add a unique CNAME record.

With the first e-mail server I moved, I chose the first option. I simply created a new HTML file with the unique string Google provided, and uploaded it to my Web server. This was very simple and very quick.

This time, I chose to create a new CNAME entry in my DNS zones. This is also fairly simple to do, and is actually good practice for modifying your MX records when the time comes. If you choose this method, you’ll be one step ahead of the game when it comes time to modify your MX records, as you’ll already know for certain where your DNS zone file is located and how to modify it. This method will take a bit longer, though, than using a simple HTML file. However, on the plus side, this method doesn’t clutter your Web server with additional files.

If you are using Site5 hosting, you’ll find your DNS zone file by accessing the SiteAdmin panel for your domain, then clicking the “Manage My Domains” tab on the left menu and choosing “DNS Zone Files.” Keep in mind that, even if your domain is registered with someone other than your Web host, the detailed DNS entries are actually handled by your Web host. In my case, my domain is actually registered with Network Solutions, but the only things I am able to modify through Network Solutions are the actual DNS addresses. Anything beyond that (CNAME records, MX records, etc.) are all handled on the other end with my Web host.

If you use the CNAME modification method, you can move onto the next steps before the CNAME change has propagated, but you won’t know for sure that everything is going to work properly until that propagation is completed.

Google has prepared a guide to walk you through the remaining steps. The guide provides pretty good information, but it’s somewhat long-winded (rightfully so, since it’s providing you with all of the information you need to set up the whole thing).

Setting Up Your E-mail Server

06-create-users

The next step is to set up the URI you want to use to access Webmail. In most cases, this is either webmail.example.com or simply mail.example.com. To make this change, click on the “Service Settings” tab in the top menu of the dashboard. Then, click “Email.” From there, specify that you want to use a custom URL, and enter the appropriate subdomain for your domain. Submit that form, and Google will then provide you with information about adding a CNAME entry for your new subdomain.

Once you have done that, return to your dashboard. You should check your current list of e-mail accounts and create a corresponding Google Apps account (under the “Users and groups” tab in the Dashboard) for each.

07-setting-mx-records

MX Record Changes

Once you have finished creating all of the users, you can return to the dashboard and click “Activate email.” Follow the MX change instructions provided by Google. If you’re fortunate enough to use one of the hosts included in the dropdown menu there, you should be able to get clear, specific instructions explaining how to make the changes in your host’s control panel. My host is not included in the list, so I had to use the generic instructions.

Google will have you add seven new MX records to your DNS zone file. Those entries will probably look like:

MX Server address Priority
ASPMX.L.GOOGLE.COM. 10
ALT1.ASPMX.L.GOOGLE.COM. 20
ALT2.ASPMX.L.GOOGLE.COM. 20
ASPMX2.GOOGLEMAIL.COM. 30
ASPMX3.GOOGLEMAIL.COM. 30
ASPMX4.GOOGLEMAIL.COM. 30
ASPMX5.GOOGLEMAIL.COM. 30

08-site5-dns-zone-fileIt’s important that you copy and paste those addresses exactly as they appear in the Google instructions. They all include dots at the end of the addresses, and that dot needs to be included.

If your DNS control panel looks like the one provided by Site5, your new entries will need to look similar to:

@ IN MX 10 ASPMX.L.GOOGLE.COM.

Where the @ symbol is in the first spot, the second spot is left blank, the word “IN” is in the third spot, the fourth spot is filled with “MX”, the fifth spot is the “priority” and the last spot includes the address provided by Google.

Also, in the case of Site5, you can only add four entries to the zone file at a time, so you’ll have to add the first four, then save the file, then add the other three.

Once you’ve made those changes, click the “I’ve made these changes” button in the Google Apps window.

Conclusion and Resources

At this point, you’re pretty much done. You now simply have to play “the waiting game.” It can take anywhere from one hour to 48 hours before the changes are complete.

Once the changes have completed, though, you can set up your e-mail client (Outlook, Thunderbird, Evolution, etc.) to check your e-mail. The Gmail IMAP settings are fairly simple. They are as follows:

IMAP (incoming) mail:

  • Server: imap.gmail.com
  • Port: 993
  • Encryption: SSL

SMTP (outgoing) mail:

  • Server: smtp.gmail.com
  • Port: 465 or 587
  • Encryption: TLS

Google provides good instructions for this set up, including specific instructions for certain e-mail clients.

I initially used some instructions from the Site5 user forums to figure out how to do this. Thanks to lenwood for putting those instructions together. I couldn’t have done this without his guide.

I also used the Mx Toolbox to occasionally check the status of my DNS zone changes. The tool was extremely helpful.

Edit: It should also be noted that you can set up custom subdomains for the other Google App services (calendar, docs, etc.) by following the same steps you followed to set up your custom Webmail subdomain. For instance, if you want to use calendar.example.com to access your Google Apps calendar, you can add a new CNAME record for “calendar” by following the steps listed under “Service Settings -> Calendar” in the Google Apps dashboard.

Quoted from: Curtiss @ htmlcenter.com

Send email using GMail SMTP server from PHP page

Just a reminder for myself and for those readers out there who need to send email from a google hosted email address.

<?php

       require_once "Mail.php";

        $from = "<from.gmail.com>";
        $to = "<to.yahoo.com>";
        $subject = "Hi!";
        $body = "Hi,\n\nHow are you?";

        $host = "ssl://smtp.gmail.com";
        $port = "465";
        $username = "<myaccount.gmail.com>";
        $password = "password";

        $headers = array ('From' => $from,
          'To' => $to,
          'Subject' => $subject);
        $smtp = Mail::factory('smtp',
          array ('host' => $host,
            'port' => $port,
            'auth' => true,
            'username' => $username,
            'password' => $password));

        $mail = $smtp->send($to, $headers, $body);

        if (PEAR::isError($mail)) {
          echo("<p>" . $mail->getMessage() . "</p>");
         } else {
          echo("<p>Message successfully sent!</p>");
         }

    ?>  <!-- end of php tag-->
hope this helps somebody :)
quote: stackoverflow.com