Home > Tutorial > PHP Mail using Gmail SMTP Tutorial

PHP Mail using Gmail SMTP Tutorial

Alright, this was one of the queries I got a few days back. I finally got the time to pour some time on it.

So here is the tutorial for sending PHP Mail using Gmail as your SMTP engine.

First of you all, I’m going to pretend that you’re familiar with a few things:

  • PHP (you know, PHP: Hypertext Preprocessor). Its a lovely language for developing webpages. If you already knew that, then good. If not, you might want to read a good PHP Tutorial.
  • A local apache+PHP webserver running to test with. I use either XAMPP or WAMPServer, while on Windows Vista. Or install LAMP stack in Ubuntu.
  • Can edit your PHP.ini configuration file. (If you don’t know what I’m talking about, get really familiar with the above two.

K, here goes.

  1. If you haven’t done so already, get a PHP server running.
  2. Download PHP-Mailer (they also have other php software for easy form-to-email).
  3. Go to your C:\xampplite\htdocs folder (in XAMPP) or C:\wamp\www folder (in WAMP), and extract the PHP Mailer into it. I’ll call this folder Root from now on.
  4. Now go to Root\PHP-Mailer\examples\, and open up test_smtp_gmail_basic.php.
  5. Now you shall have to do some minor editing. Don’t worry, its majorly minor. Just change the Emails to your send and receiver, and type your password. Here’s what mine almost looks like. Almost. Thats not the password. … I think.

Open and edit test_smtp_gmail_basic.php

Open and edit test_smtp_gmail_basic.php


$mail->IsSMTP(); // telling the class to use SMTP

$mail->Host       = "stmp.gmail.com"; // SMTP server

$mail->SMTPDebug  = 1;                     // enables SMTP debug information (for testing)

// 1 = errors and messages

// 2 = messages only

$mail->SMTPAuth   = true;                  // enable SMTP authentication

$mail->SMTPSecure = "ssl";                 // sets the prefix to the servier

$mail->Host       = "smtp.gmail.com";      // sets GMAIL as the SMTP server

$mail->Port       = 465;                   // set the SMTP port for the GMAIL server

$mail->Username   = "vishalkumar@gmail.com";  // GMAIL username

$mail->Password   = "topsecretpassword:D";            // GMAIL password

$mail->SetFrom('vishalkumar@gmail.com', 'Vishal Kumar');

$mail->AddReplyTo("vishalkumar@gmail.com","Vishal Kumar");

$mail->Subject    = "Hey, check out http://www.vishalkumar.in";

$mail->AltBody    = "Hey, check out this new post on www.vishalkumar.in"; // optional, comment out and test

$mail->MsgHTML($body);

$address = "vishalkumar@gmail.com";

$mail->AddAddress($address, "Vishal Kumar");

  1. Now, pressing save, you’ll be half done with this little tutorial. Ok, the actual step is you need to edit your PHP.ini file settings. You can find that C:\xampplite\php if you are into XAMPP. Here you need to open the PHP.ini file, then search for “openssl”. Go ahead and take that ‘;’ comment symbol from the start of the line. In WAMP, all you need is your mouse. Just click on the speedometer icon of WAMPServer in the taskbar. Go to PHP>PHP Extensions and click on php_openssl to turn it on

Enable the php_openssl.dll extension by taking off the ';'

Enable the php_openssl.dll extension by taking off the ';' in XAMPP



Tick to enable php_openssl in WAMP

Tick to enable php_openssl in WAMP


  1. Restart your servers services. This should be fairly simple
  2. Go navigate to http://localhost/PHP-Mailer/examples/test_smtp_gmail_basic.php in your browser. And then check your Receivers Inbox. Hi!!!

Thats about it; thats how I managed to send emails using GMail’s SMTP engine to any mail, through PHP.

Note though, this tutorial is meant to be a specific reply to a certain query I got, but I figured more people would want to read this, so I posted it up.

If you have any doubts, or extensions, or any helpful suggestions, comment up. :)

Share and Enjoy:
  • email
  • PDF
  • Google Bookmarks
  • TwitThis
  • Facebook
  • IndianPad
  • Slashdot
  • StumbleUpon
  • Technorati
  • Yahoo! Buzz
  • del.icio.us
  • Live
Categories: Tutorial Tags: , ,
  1. saliya
    August 3rd, 2009 at 13:03 | #1

    Hey dude thx very very much this post really helpedme alooooooootttttttttttt :-) u r the best

    • Venki
      February 8th, 2011 at 14:23 | #2

      Hi, its nice to see your blog. can any one enter IIMB to see such an exiting place??

  2. manu
    August 5th, 2009 at 07:05 | #3

    <?php
    //require("phpmailer/class.phpmailer.php");
    include("phpmailer/class.phpmailer.php");
    $mail = new PHPMailer();
    $mail->Host = "ssl://smtp.gmail.com::465";
    $mail->SMTPSecure = "ssl";
    $mail->IsSMTP(); // send via SMTP
    IsSMTP(); // send via SMTP
    $mail->SMTPAuth = true; // turn on SMTP authentication
    $mail->Username = "mygmailaccount@gmail.com"; // SMTP username
    $mail->Password = "mygmailaccountpassword"; // SMTP password
    $webmaster_email = "mygmailaccount@gmail.com"; //Reply to this email ID
    $email="mygmailaccount@gmail.com"; // Recipients email ID
    $name="name"; // Recipient's name
    $mail->From = $webmaster_email;
    $mail->FromName = "Webmaster";
    $mail->AddAddress($email,$name);
    $mail->AddReplyTo($webmaster_email,"Webmaster");
    $mail->WordWrap = 50; // set word wrap
    $mail->AddAttachment("/var/tmp/file.tar.gz"); // attachment
    $mail->AddAttachment("/tmp/image.jpg", "new.jpg"); // attachment
    $mail->IsHTML(true); // send as HTML
    $mail->Subject = "This is the subject";
    $mail->Body = "Hi,
    This is the HTML BODY "; //HTML Body
    $mail->AltBody = "This is the body when user views in plain text format"; //Text Body
    if(!$mail->Send())
    {
    echo "Mailer Error: " . $mail->ErrorInfo;
    }
    else
    {
    echo "Message has been sent";
    }
    ?>

    am getting follwing errors…..

    Deprecated: Function eregi() is deprecated in D:wampwwwffphpMailerclass.phpmailer.php on line 594

    Warning: fsockopen() [function.fsockopen]: SSL operation failed with code 1. OpenSSL Error messages: error:140770FC:SSL routines:func(119):reason(252) in D:wampwwwffphpMailerclass.smtp.php on line 125

    Warning: fsockopen() [function.fsockopen]: Failed to enable crypto in D:wampwwwffphpMailerclass.smtp.php on line 125

    Warning: fsockopen() [function.fsockopen]: unable to connect to ssl://localhost:25 (Unknown error) in D:wampwwwffphpMailerclass.smtp.php on line 125
    Mailer Error: SMTP Error: Could not connect to SMTP host.

    thanks in advances….

    • waseem ahmed
      December 23rd, 2010 at 12:34 | #4

      thanks for ur turtorial. I have one question for u vishal.can you please tell me how to send twit to twitter using php

  3. Piyush
    August 15th, 2009 at 16:37 | #5

    hello vishal kumar,

    i m trying to install a prog. in my system but after installation when run its index.php then it shows login screen and when i type user name and password which i allready created during installation process it shows wrong user name /password message. i don't know where i m wrong but i think i m doing wrong when third step of installation ask for SMTP server IP address then user name and password.

    i m using google as a smtp server but still i don't understand what is the IP adress of SMTP server and how can i find IP adress of SMTP Server. will u please help me to install this software in my system as wel as my web server. if u wish i can send u prog. what i m installing in my system. my mail ID is classresult@gmail.com.

    • September 6th, 2009 at 17:27 | #6

      Hey, what software are you using? It might help if you put the links for it.

      And when specifying the STMP address you don't need to put in the IP Address anywhere. Its the smtp.gmail.com thats required. The DNS Servers will send the smtp.gmail.com request to the correct IP Address.

  4. manoj
    February 5th, 2010 at 08:21 | #7

    hi vishal'
    Your tutotial helped me a lot to send mail using smtp authentication in php, am using Xampp1.7.1, while trying to send error i get the following error.
    Error : authentication failure [SMTP: Invalid response code received from server (code: 535, response: authentication failed (#5.7.1))]

    but when tried to send mail using outlook, it works perfectly, please help me

  5. Yash Mistrey
    February 13th, 2010 at 12:50 | #8

    Dear Vishal!

    I am using google apps. for email.

    actually i am very confusing on web form processing.

    I couldn't able to send email from my website form to my email.

    my ISP saying to use smtp in form they saying

    ———————————————xxxxxxx———————————————

    We have disabled anonymous user to send mail, so you have to send mail through SMTP authentication and smtp details are given below:-
    Host:- mail.your_domain_name
    User name:- XXX@your_domain_name
    Password:- corresponding password
    Port :-25 or 26
    ———————————————xxxxxxx———————————————

    But is didn't work, after they saying that it is bcz of your are using google apps.

    Please reply me solution with any example.

    I read your tutorial , but, i didn't get it. right

    i want to send email from this way but this tutorial is not well explained. can you explain with any example .

    I don't know php so details.

    Please Vishal!
    I am waiting your reply.

  6. giri
    February 23rd, 2010 at 15:11 | #11

    thanks dude your tutorial is good.

  7. adunkey
    February 27th, 2010 at 20:04 | #12

    i get this error:

    Parse error: parse error in C:wampwwwPHPMailer_v5.1examplestest_smtp_gmail_basic.php on line 28
    do you change your php.ini at all??/

    • March 11th, 2010 at 03:55 | #13

      Yes, the php.ini needs to be edit. Check the tutorial again.
      For the parse error, you might have accidentally deleted a few characters or misspelled a word.

  8. March 2nd, 2010 at 10:45 | #14

    thanks buddy, thats why Indians are better than …………..

  9. rootkit87
    March 7th, 2010 at 09:42 | #15

    Thx man….
    this was the best tutorial for sending mail…

    it worked like a charm ;)

    u r the best :) :)

  10. Shil
    March 10th, 2010 at 22:19 | #16

    Hi Vishal,
    Great Tutorial, I have configured everything using your tutorial and the mail gets sent to my gmail account. Just wanted to ask you something, I have created an email form where I want to click on the Send Button and this should send an email to my gmail account, how do I do this? Will be waiting for your reply. Many thanks

    • March 11th, 2010 at 03:53 | #17

      In your email Form, you would be making use of the <form> tag and assigning it an action (the PHP mail sending page), and a method (either GET-send the data in the URL address, or POST-send it in the request itself, so it doesn't appear in the URL).

      So you'll have <form action="sendmail.php" method="post">…

      Then in your sendmail.php, you need to receive the variables.
      Access the form elements in the previous page with '$_POST['name']'. So instead of the strings in the demo email sending above, you would use the POST variables.

      • Shil
        March 12th, 2010 at 20:25 | #18

        Hi Vishal

        Thanks for your help, I managed to do it :-)

        Regards

        Shil

  11. ANIRUDH TOMER
    March 12th, 2010 at 01:26 | #19

    what you have done is good vishal but I would like to mention that u are no where using standard "mail()" function of PHP which dosen't work unless
    1> u send mail from localhost to localhost
    2> u have a registered domain on the webspace

    anyways nice tutorial…great job

  12. dax
    March 18th, 2010 at 06:36 | #20

    Hi Vishal
    I have configured everything using your tutorial and the mail net gets sent to my gmail account.
    actually it is not shown any error and not send the mail

    • May 10th, 2010 at 13:49 | #21

      Where have you hosted this? Have you started from fresh? You can also enable error messages by setting STMPDebug to 1.

      Also check out that your PHP is working by enabling error messages in php.ini (search for error_reporting ), and making sure theres a line like error_reporting = E_ALL

  13. Zaka
    March 21st, 2010 at 08:55 | #22

    it not working . wht to do of include("class.phpmailer.php");include("class.smtp.php") ?

    • May 10th, 2010 at 13:17 | #23

      Leave those. Just make the changes specified in the code above. Most of the work is already done (thanks to PHPMailer). :)

  14. Wendy
    March 27th, 2010 at 03:13 | #24

    Thank you for your useful information :-)

  15. SkyJumper
    April 20th, 2010 at 23:33 | #25

    do i need to also make changes at the php.ini at the part below?
    [mail function]
    ; For Win32 only.
    ;SMTP = localhost
    ;smtp_port = 25

    ; For Win32 only.
    ;sendmail_from = root@localhost

    • May 10th, 2010 at 13:16 | #26

      You needn't touch the mail function. This works without that. The only change you need to do is the SSL, in php.ini

  16. sourabh
    May 20th, 2010 at 02:09 | #27

    Hi vishal , i have followed instructions above but when i run test_smtp_gmail_basic.php in browser it doesn't display anything and email is not delivered. i am using wampserver 2.0 please help me out.
    Thanks.

    • May 20th, 2010 at 06:46 | #28

      Are you sure you followed instructions to the letter?
      First check that normal php pages are being displayed (i.e. wamp is running as it should). Create a test.php page in your www folder, and put in <?php echo "hi"; ?>
      Then open the page by going to your http://localhost/test.php. You should see a "hi".
      If you don't, check click on the wampserver logo and select Start All Services.
      If you have started the services and you were just thinking that yada yada yada I've already done all of that, please make sure that you've edited the php.ini page.
      If even that doesn't work, try using XAMPP, and try with the same instructions.

  17. swapnesh
    December 15th, 2010 at 20:56 | #29

    i tried all your instructions but still getting following error while creating new tickets.
    Warning: mail() [function.mail]: SMTP server response: 501 5.5.4 Invalid Address in C:Inetpubwwwrootosticket_1.6.0uploadincludepearMailmail.php on line 128

  18. hus
    January 3rd, 2011 at 16:38 | #30

    got this error. can u help me?

    SMTP -> ERROR: Failed to connect to server: Unable to find the socket transport "ssl" – did you forget to enable it when you configured PHP? (104113184)
    SMTP Error: Could not connect to SMTP host. Mailer Error: SMTP Error: Could not connect to SMTP host.

  19. Furqan
    February 14th, 2011 at 11:00 | #31

    I found this error
    SMTP Error: Could not connect to SMTP host. Message was not sent.Mailer error: SMTP Error: Could not connect to SMTP host.

  20. Farooq
    February 22nd, 2011 at 01:04 | #32

    very good tutorial vishal..
    i had some problems in php versions initially but got over 'em..
    Great work!!

  21. kishan illur
    March 19th, 2011 at 20:38 | #33

    Hi Vishal, can i use this code to send an email to my gmail account from the website i have host…? if yes, could u tel me the way to do it…?

  22. -me
    April 3rd, 2011 at 01:46 | #34

    Thanks buddy. It has helped me and gifted me a smiley face. :-) This one is for you.

    Thanks again

  23. Shashwat
    May 27th, 2011 at 03:24 | #35

    I got the following error:

    SMTP -> ERROR: Failed to connect to server: Unable to find the socket transport "ssl" – did you forget to enable it when you configured PHP? (24439416)
    SMTP Error: Could not connect to SMTP host. Mailer Error: SMTP Error: Could not connect to SMTP host.

  24. ashok
    June 1st, 2011 at 00:52 | #36

    thanks boss

  25. Hendra
    June 26th, 2011 at 12:26 | #37

    hii Vishal,
    i have followed instructions above but when i run test_smtp_gmail_basic.php,
    but i get this error :
    "SMTP -> ERROR: Failed to connect to server: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond. (10060)
    SMTP Error: Could not connect to SMTP host. Mailer Error: SMTP Error: Could not connect to SMTP host."

    why this happen?can you help me,please….

  26. dila
    July 2nd, 2011 at 13:15 | #38

    thank you so much for your effort by making this tutorial..
    i have been looking for this solution almost 3 weeks..
    now i can finish my final year project..
    thanks again..

  27. amit dubey
    July 21st, 2011 at 22:12 | #39

    thanks dear,you really wrote all these steps very clearly,
    i again really-2 thankful to you
    -amit dubey
    New Delhi,India

  28. Sony.k
    July 24th, 2011 at 22:37 | #40

    <?php
    $to = "sony@gmail.com";
    $subject = "Test mail";
    $message = "Hello! This is a simple email message.";
    $from = "sony@gmail.com";
    $headers = "From:" . $from;
    mail($to,$subject,$message,$headers);
    echo "Mail Sent.";
    ?>

    In php.ini

    [mail function]
    ; For Win32 only.
    ; http://php.net/smtp
    SMTP = smtp.gmail.com
    ; http://php.net/smtp-port
    smtp_port = 465

    auth_username = sony
    auth_password = asdsa

    pop3_server = smtp.gmail.com
    pop3_username = sonyi
    pop3_password = asdsa

    Still its not working . Please mail me at isprivacy@gmail.com with correct solution.
    Thanks
    Sony.K

  29. todo
    August 19th, 2011 at 00:05 | #41

    hello Vishal!

    I am using google apps. for email. and i am try to send mail by using phpmailer.
    my php code has work good with my gmail account like abc@gmail.com.
    but when i am try to send mail with my google apps email like abc@owndomain.com, it's not worked.

    so please tell me which extra setting i have to done to send mail.?

    thanks

  30. Ashish
    September 3rd, 2011 at 20:18 | #42

    Thank you so much..I am very happy… I had googled for total 20 hours "how to send main using php script?"..
    But all in vain.. At last your post helped me to get rid of my problem…
    For the time being its working very fine.. :D :D :D

  31. Ashish
    September 3rd, 2011 at 20:20 | #43

    Thank you so much..I am very happy… I had googled for total 20 hours "how to send main using php script?"..

  32. alisha
    September 15th, 2011 at 18:04 | #44

    Do i need to edit anything on php.ini file and php extension php_open_ssl but nothing is being displayed what we need to write in include_path in php.ini file i don't know what we need to edit in php.ini. i have followed all your instructions but blank page is being displayed when i open http://localhost/phpmailer/PHPMailer_5.2.0/examples/test_smtp_gmail_basic.php page.

  33. Wut Yee Tun
    October 5th, 2011 at 10:58 | #45

    thanks u so much buddy your tutorial is so Cool. :-)

  1. No trackbacks yet.
You must be logged in to post a comment.