UPDATE: Send email with PHP and GMail hosted for your domain

Due to the amount of requests emailed to me for working source code I have now posted the modified PHPMailer I use in my own projects. Click here to download the library. Here’s an example of how to use the code:

require_once('/phpgmailer/class.phpgmailer.php');
$mail = new PHPGMailer();
$mail->Username = 'user@domain.com';
$mail->Password = 'password';
$mail->From = 'user@domain.com';
$mail->FromName = 'User Name';
$mail->Subject = 'Subject';
$mail->AddAddress('myfriend@domain.com');
$mail->Body = 'Hey buddy, here's an email!';
$mail->Send();

This will work for any GMail or Google Hosted email account. Just make sure to include the @domain.com part for the username, even if it’s for standard GMail. Hope this saves people some hastle.

[tags]gmail, php, google, phpmailer[/tags]

67 Responses to “UPDATE: Send email with PHP and GMail hosted for your domain”


  1. 1 Nick Van Dorsten

    I’d have to recommend Swiftmailer by d11wtq from the PHP developers network… it’s much smaller than phpmailer, and is much, much faster (1000+ emails per minute), its plugin system is second to none.

    http://www.swiftmailer.org

  2. 2 KbronCT

    I’m sorry to say this, but I get this errors:

    I’m using your modified PHPmailer and a very simple PHP code based on your example.

    require_once(’phpgmailer/class.phpgmailer.php’);
    $mail = new PHPGMailer();
    $mail->Username = ‘test@gmail.com’;
    $mail->Password = ‘****’;
    $mail->From = ‘XXX@gmail.com’;
    $mail->FromName = ‘test User Name’;
    $mail->Subject = ‘Test Subject’;
    $mail->AddAddress(’YYYY@gmail.com’);
    $mail->Body = ‘Hey buddy, heres an email!’;
    $mail->Host = ’smtp.gmail.com’; //
    $mail->Port = 465; //
    //$mail->Mailer = ’smtp’; //
    //$mail->SMTPAuth = true; //
    $mail->Send();

    if(!$mail->Send())
    {
    echo “Message could not be sent. “;
    echo “Mailer Error: ” . $mail->ErrorInfo;
    exit;
    }
    echo “Message has been sent”;

    Well, I get:

    >>Message could not be sent.
    >>Mailer Error: The following From address failed: XXXt@gmail.com

    “From adress” always fails, whatever I try.

    I have to use this or I get a fsock() error:
    $mail->Host = ’smtp.gmail.com’; //
    $mail->Port = 465; //

    Thank you in advance!!!

  3. 3 pvulgaris

    KBronCT, the reason that it didn’t work for you is because you tried to overide the default Host and Port fields for the $mail object. You ONLY have to change/edit the fields that I show in my example.

  4. 4 KbronCT

    Thank you very much!

    I’ll try tomorrow and see…

  5. 5 pcmattman

    Um… is it just me or does everyone else get a 404 when they click on the link to download?

  6. 6 pvulgaris

    Sorry about that, link is fixed now.

  7. 7 Jiby

    Error:
    Warning: fsockopen() [function.fsockopen]: unable to connect to smtp.gmail.com:465 in /home/***/public_html/phpmailer/class.smtp.php on line 105
    Message was not sent. Mailer Error: Language string failed to load: connect_host

    Code:
    Username = “***@gmail.com”;
    $mail->Password = “***”;
    $mail->From = “test@test.com”;
    $mail->FromName = “Tester”;
    $mail->Subject = “TEST”;
    $mail->Body = “This is a test”;
    $mail->AddAddress(”***@yahoo.com”);
    if (!$mail->Send()) {
    echo “Message was not sent. “;
    echo “Mailer Error: ” . $mail->ErrorInfo;
    } else {
    echo “Message has been sent.”;
    }
    ?>

  8. 8 jjo9728

    first things first . . . this is awesome. got it to work without any problems.

    that being said, how would i send it to a dynamic email address and include dynamic variables in the body?

    thanks pvulgaris - great tool!

  9. 9 brk

    I also get this error:

    Warning: fsockopen() [function.fsockopen]: unable to connect to smtp.gmail.com:465 in /home/***/class.smtp.php on line 105

    Any recommendations much appreciated.

  10. 10 Manuel R.G.

    Thanks for your script. It works perfect for me!

  11. 11 balhau

    I had that last error too!

  12. 12 balhau

    I also have this problem:

    Warning: fsockopen(): no SSL support

    how do I enable SSL support.
    I had run the phpinfo() function and the output tells that the SSL is enabled. I don’t know how to solve this problem!

  13. 13 dimitris

    I receive this error

    Message was not sentMailer Error: Language string failed to load: from_failedfrom@email.com

  14. 14 sb

    Yesh! Thanks a lot! This post has saved tons of my time!

  15. 15 mm

    I receive this error:
    Warning: fsockopen() [function.fsockopen]: unable to connect to ssl://smtp.gmail.com:465 (Unable to find the socket transport “ssl” - did you forget to enable it when you configured PHP?) in D:\WindowsApacheMySQLPHP\www\PHP\phpgmailer\class.smtp.php on line 105
    What’s going on?

  16. 16 mm

    Also, when I look at phpinfo(), it has no mention whatsoever of SSL.

  17. 17 Rashad

    Thank you so much for this solution. I’ve been scouring the net for days trying to figure this out until I found this post. Umm, google, do a better job of finding this post! I’ll add some more keywords.

    installing php phpmailer php_mail google gmail google apps your my domain

    Thanks again!

  18. 18 INTPnerd

    I am also not able to get this to work:

    PHP Warning: fsockopen(): no SSL support in this build in C:\www\phpHelpers\phpgmailer\class.smtp.php on line 105

    PHP Warning: fsockopen(): unable to connect to smtp.gmail.com:465 in C:\www\phpHelpers\phpgmailer\class.smtp.php on line 105

    here is the code I am using:

    $mail = new PHPGMailer();
    $mail->Username = ‘****@gmail.com’;
    $mail->Password = ‘*********’;
    $mail->From = ‘****@gmail.com’;
    $mail->FromName = ‘Me Me’;
    $mail->Subject = ‘email test’;
    $mail->AddAddress(’*****@hotmail.com’);
    $mail->Body = ‘here is an email!’;
    $mail->Send();

    any ideas?

  19. 19 str

    PHP Warning: fsockopen(): no SSL support in this build in C:\www\phpHelpers\phpgmailer\class.smtp.php on line 105

    php must be compiled with –with-openssl

  20. 20 rekha

    my code is as follows and I am getting following error.

    Message was not sent
    Mailer Error: The following From address failed: rekhakulka@gmail.com

    SetLanguage(’en’,'c:/phpmailer/language/’);
    $mail->PluginDir = “c:/php/”;

    $mail->IsSMTP(); // send via SMTP
    $mail->Host = “smtp.gmail.com”; // SMTP servers
    //$mail->SMTPAuth = “true”; // turn on SMTP authentication
    $mail->Username = “rekhakulka@gmail.com”; // SMTP username
    $mail->Password = “kalavati”; // SMTP password
    //$mail->Port = 465;

    $mail->From = “rekhakulka@gmail.com”;
    $mail->FromName = “Rekha”;
    $mail->AddAddress(”rekha_harnoor@yahoo.com”);

    $mail->IsHTML(true); // send as HTML

    $mail->Subject = “Here is the subject”;
    $mail->Body = “This is the HTML body“;
    $mail->AltBody = “This is the text-only body”;

    if(!$mail->Send())
    {
    echo “Message was not sent “;
    echo “Mailer Error: ” . $mail->ErrorInfo;
    exit;
    }

    echo “Message has been sent”;
    ?>

  21. 21 luca

    Great!!!!Good script!!!!!

  22. 22 Alex

    After all the changes, What is the final script then???

  23. 23 Monia

    Thank for this script - it works but not on every server :( I put this script on two different servers - on first it works perfectly, on second there’s an error:

    Warning: fsockopen() [function.fsockopen]: unable to connect to ssl://smtp.gmail.com:465 (Connection refused) in /homepages/39/d164239424/htdocs/http_docs/phpgmailer/inc/class.smtp.php on line 105
    Message could not be sent.

    Mailer Error: SMTP Error: Could not connect to SMTP host.

    I think it has something to do with php configuration on server, but I don’t know how to fix that. I will be gratefull for any ideas :)

  24. 24 pvulgaris

    Monia, double check that your have the OpenSSL package installed for PHP. Look here for more information.

  25. 25 Adegas

    Grrr…
    I have the page with code bellow inside directory phpmailer.

    IsSMTP(); // send via SMTP
    $mail->Host = “smtp.gmail.com”; // SMTP servers
    $mail->SMTPAuth = true; // turn on SMTP authentication
    $mail->Username = “josefadegas”; // SMTP username
    $mail->Password = “xxxxxxx”; // SMTP password

    $mail->From = “josefadegas@gmail.com”;
    $mail->FromName = “Testar”;
    $mail->AddAddress(”josefadegas@yahoo.com”);
    //$mail->AddAddress(”ellen@site.com”); // optional name
    //$mail->AddReplyTo(”info@site.com”,”Information”);

    $mail->WordWrap = 50; // set word wrap
    //$mail->AddAttachment(”"); // attachment
    //$mail->AddAttachment(”");
    $mail->IsHTML(true); // send as HTML

    $mail->Subject = “titulo”;
    $mail->Body = “This is the HTML body“;
    $mail->AltBody = “texto”;

    if(!$mail->Send())
    {
    echo “Message was not sent “;
    echo “Mailer Error: ” . $mail->ErrorInfo;
    exit;
    }

    echo “Message has been sent”;
    ?>

    And always give me this error:
    Message was not sent

    Mailer Error: The following From address failed: josefadegas@gmail.com

    Help me please

  26. 26 Dima

    I got next error: SMTP Error: Could not connect to SMTP host.
    I found in my phpinfo next:
    openssl
    OpenSSL support enabled
    OpenSSL Version OpenSSL 0.9.8d 28 Sep 2006

    Help me please

  27. 27 marques

    Thanks, it worked for me!!! I just had to enable openssl.

  28. 28 Usman

    Hi, Dear, i got phpmailer working on my local machine, i enabled openssl by using ini_set() function and it worked for me.
    When i put the same files on my webhost, error occurred
    Mailer Error: Language string failed to load: connect_host
    can anyone help me solving this error? plz help me! Bye

  29. 29 jzxrcrgnkv

    Hello! Good Site! Thanks you! olcxrrauqanz

  30. 30 Sudhanshu

    I don’t have words to express how grateful I am to you for having done this.

    I have a deadline tomorrow, and had spend almost the whole night trying to get this to work (It’s almost 4). I found you page about 10 minutes back, and now it’s done :D

  31. 31 Florian

    Thanks a lot.. it is working like a charm.

  32. 32 Alexandru

    I got PHP Version 5.1.6, OpenSSL 0.9.8b 04 May 2006.
    I get the famous error:
    Warning: fsockopen() [function.fsockopen]: unable to connect to ssl://smtp.gmail.com:587 (Permission denied) in /var/www/html/system/phpmailer/class.smtp.php on line 107
    Mailer Error: Language string failed to load: connect_host
    Any Ideas?

  33. 33 sohail

    I solute the person who re-wrote the phpmailer class for google mail, i have been looking for this for the past good two weeks. Nothing works, no matter what i tried. Opened number of threads on various website no one has a clue.

    However the jigsaw puzzled is solved. Make sure just copying and overwritting your phpgmailer from this website won’t solve your problem.

    Here are few steps make sure you performed this before scratching your head?

    Php.ini

    1) Specify your php extension folder probably on line 524.
    extension_dir =”C:\Program Files\PHP\ext” or of your choice.

    2) uncomment
    ;extension=php_openssl.dll probably on line 668.

    3) and make sure you copied (php_openssl.dll) under this directory.
    extension_dir =”C:\Program Files\PHP\ext” or of your choice from above.(1)

    4) restart apache

    5) open command prompt (CMD) and type php -v, see if it says any missing files, copy those missing files.

    in your mail just use this lines and please don’t specify SMTPAuth and Port. Its already taken care inside the revised copies of phpgmailer and smtp class files.

    $mail->IsSMTP(); // send via SMTP
    $mail->Host = “ssl://smtp.gmail.com”; // SMTP servers
    //$mail->SMTPAuth = “true”; // Not required
    $mail->Username = “xxx@googlemail.com”; // SMTP username
    $mail->Password = “xxx”; // SMTP password
    //$mail->Port = 465; // Not Required

    Hope this helps someone.

  34. 34 meaw

    Hai,

    I am having this error Pls mail me how to correct it,

    mail id hiranvnath@gmail.com

    Warning: fsockopen() [function.fsockopen]: unable to connect to ssl://smtp.gmail.com:465 (Unable to find the socket transport “ssl” - did you forget to enable it when you configured PHP?) in C:\wamp\www\phpgmailprog\phpgmailer\class.smtp.php on line 105

    Pls find a way to correct it

  35. 35 Sridhar

    Hello,
    Words won’t be sufficient to thank you. First I tried to send mail with inbuilt mail(), no success. After some time tried phpmailer, tried to use local host, my isp’s host, nothing worked. On this and third attempt, it worked. Only effort involved was, downloading your library, copying the code, changing the appropriate fields and voila it worked.
    I was preparing myself for a long battle with this, but your library prevented a war :).
    Thanks and keep going.

  36. 36 Erick S

    Thanks, man. You saved me some serious headaches with this class :)

  37. 37 Logic

    Great script, works like a charm. Now I can move on to step 3 of my project, formatting an email for an outlook calendar event.

    Thanks again, really good work.

  38. 38 kenny H

    Hi,
    I got the folowing error(s):

    * warning: fsockopen() [function.fsockopen]: unable to connect to ssl://smtp.gmail.com:465 (Permission denied) in /var/www/html/weblog/sites/all/modules/smtp/smtp.module on line 1878.

    * warning: fsockopen() [function.fsockopen]: php_network_getaddresses: getaddrinfo failed: Name or service not known in /var/www/html/weblog/sites/all/modules/smtp/smtp.module on line 1878.

    * warning: fsockopen() [function.fsockopen]: unable to connect to ssl://:465 (Unknown error) in /var/www/html/weblog/sites/all/modules/smtp/smtp.module on line 1878.

    I fear i forgot to configure something on my fedora installation. Can somebody please help me further?

    best regards,

  39. 39 Ted Conn

    Great script! However, the “Sender” variable doesnt seem to register appropriately. Reply-to is always the same as the sender address. This one little flaw pretty much prevents me from using this class on a more advanced level.

  40. 40 Code

    Great tip, I like your script.
    Do you have any idea if there is there is a limit to emails sent ?
    I want to use gmail as my default smtp sever and I want to be sure that I will not get banned or emails will note be sent because of to many mails sent.
    Thanks

  41. 41 Tanvir

    WHY M I GETTING THIS. HOW TO ENABLE SSL.I m geting the following error.

    Failed to connect to ssl://smtp.mail.yahoo.com:465 [SMTP: Failed to connect socket: Unable to find the socket transport “ssl” - did you forget to enable it when you configured PHP? (code: -1, response: )]

  42. 42 David F

    Kenny,

    I had experienced exactly the same problem:
    * warning: fsockopen() [function.fsockopen]: unable to connect to ssl://smtp.gmail.com:465 (Permission denied) in /var/www/html/…/sites/all/modules/smtp/smtp.module on line 1878.

    I also had the following error message:
    Error sending email: “SMTP Error: Could not connect to SMTP host.” From: “xxxxxxxx@gmail.com”

    I simply disabled SELinux via Security Level COnfiguration tool, the problem went away.

    Hope it’d help.

    David

  43. 43 Dimitris

    Is it possible to use this with google apps for domains?
    I have a domain hosted at google but i alwasy get this error when I try:

    Message was not sent. Mailer Error: The following From address failed: name@domain.com

  44. 44 Sudhanshus

    I had used this very script to get Google Apps running on my server, but unfortunately I have had to remove it some time back.

    I just wanted to share why I had to do so.

    A very little known fact is that if you send over 500 emails a day, Google assumes that you are a spambot and stops your services. Of course, there are no emails to tell you that this has happened.

    I found out that it wasn’t working when I realized that the number of people clicking on the activation link had dropped to about 0% :)

    About 2000 people registered on the site in over two weeks, so the number of emails was way below what Google’s self imposed limit of 500 a day. But you can’t fight google can you? After all, there not the ones who are evil.

    So if you are starting with Gmail or Google Apps take the above into account before you shift completely. It just might not be worth the effort.

    In all other cases, this script is god sent.

    Much love..

  45. 45 Sudhanshus
  46. 46 marcg

    I used the basic example shown at the begining and I checked also the module OpenSSL (enabled) but it does not work for me ! I have a problem of connection timed out. See below:

    “Warning: fsockopen() [function.fsockopen]: unable to connect to ssl://smtp.gmail.com:465 (Connection timed out) in /home/mywishli/ma-liste-cadeaux/include/phpgmailer/class.smtp.php on line 105″

    I tried and tried again but no solution. Please HELP !

  47. 47 RooZ

    @str
    PHP Warning: fsockopen(): no SSL support in this build in C:\www\phpHelpers\phpgmailer\class.smtp.php on line 105

    php must be compiled with –with-openssl

    I have OpenSSL, php_openssl, and ssl_module for Apache, and I’m getting this error. I’m using Windows and wamp, so compiling it will suck.

  48. 48 Jo

    I receive this error:

    Warning: fsockopen(): no SSL support in this build in \class.smtp.php on line 105

    Warning: fsockopen(): unable to connect to smtp.gmail.com:465 in ….class.smtp.php on line 105

    I use SSL in my email setting, it not working otherwise.

    Under the territory
    C:\Program Files\EasyPHP1-8\php\extensions
    i have php_openssl.dll file, version of 14/12/2004

    In my php.ini:
    extension=php_openssl.dll is uncomment

    I have also set this variable:
    extension_dir: C:\Program Files\EasyPHP1-8\php\extensions

    I don’t know what to do? :(

    Any suggestion?

    I am using Windows ME, do i need to compile if yes, how do i compile php?

    Thanks

  49. 49 Jo

    I have run phpinfo,

    What should i have in the variable:
    _SERVER[”SERVER_SIGNATURE”], in the mailto should i have my email, or
    Apache/1.3.33 Server at ….. Port is ok?

  50. 50 gunhan

    i have a problem like this and i need help.

    here is the error code

    Warning: fsockopen() [function.fsockopen]: unable to connect to ssl://smtp.gmail.com:465 (Unable to find the socket transport “ssl” - did you forget to enable it when you configured PHP?) in C:\Program Files\Apache Group\Apache2\htdocs\yeniproje\class.smtp.php on line 105

  51. 51 diane lawrence

    I am fu %$#$%^ &&^%^$ madd I have tried 50 user names and gmail won’t take them I want to do something really unchristian HELPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP

    di

  52. 52 hijas

    i am getting the following error while running plz help me……
    Fatal error: Maximum execution time of 30 seconds exceeded in C:\wamp\www\DocumentRoot\class.smtp.php on line 1033

  53. 53 Cozzy

    I know there hasnt been many ppl answering these questions but i too was having the fsockopen problem. I uncommented the php_openssl adn tried to use this code@

    Username = ‘*****@gmail.com’;
    $mail->Password = ‘*****’;
    $mail->From = ‘*****@gmail.com’;
    $mail->FromName = ‘Me’;
    $mail->Subject = ‘Test’;
    $mail->AddAddress(’*******@hotmail.com’);
    $mail->Body = ‘Hey buddy heres an email!’;
    if (!$mail->Send()) {
    echo “Message was not sent. “;
    echo “Mailer Error: ” . $mail->ErrorInfo;
    } else {
    echo “Message has been sent.”;
    }
    ?>

    This time it said message was sent. although no mail was actually recieved! Just hoping someone who has it working may spread a bit more light to the many of us that havent got it working yet.

  54. 54 TT

    I am getting the following error sending to yahoo.com via gmail.com very frequently.

    SMTP Error: Could not connect to SMTP host.

    But sometimes it works. So there is more than just my setup because it has worked but just not all the time. Anyone has similar problem?

    TT

  55. 55 Cengizhan

    Great work. It worked seamlessly with 5 mins of copy paste work. Now I need to send html messages. How to arrange it?

  56. 56 unknown

    i am getting error code 102 when i log into gmail and its letting me see my gmail but i cand refresh anything

    “oops gmail has enountered an error # 102″

    i think thats what it says or somthing similar

  57. 57 Peter Hartree

    Thank you for this script, hugely appreciated.

  58. 58 Leoloko! hehe

    how do make this script in localhost server???????

    pleaseeeeeeeeeeeeeeeeeeeeeee

  59. 59 eathaiku

    Many Thanks, wish I would have found this earlier; wasted half a day trying to get PEAR::Mail to work.

  60. 60 China Landscape

    It’s workin well for me with my gmail account but the problem is that it takes long time to send the email (about 5sec.)

    Is it normal? Does someone know a solution to this problem?

    Thanks!

  61. 61 Chris

    I’m with Ted Conn.

    the Reply-To has to be set to a different Email address for my application of this mailer… and it seems I can’t change that.

    Anyone found a way around this yet?

  62. 62 KK

    I use PHPMailer with the following setting. But you have to get the version of PHPMailer that support SMTSecure.

    $this->Mailer = “smtp”;
    $this->Port = ‘465′;
    $this->SMTPSecure = ‘tls’;
    $this->SMTPAuth = true;

    Once a while I get the following error.

    “454 4.7.0 Cannot authenticate due to temporary system problem. Try again later.”

    It means that Gmail requires me to manually login to Gmail and type in the verification text to make sure that I am a human. Does anyone have this problem?

    One way to get around the 500 email limit is to set up a few Gmail accounts and send the emails using a different account each time. But I am not sure the Google would like that.

  63. 63 JENSEN

    All of u guys are genius bt i had problem my mail cant reach on the other side although it show mail sent.
    what should i do?
    Please help. Thanks

  64. 64 Don Deskins

    Great script! Love it!

    Something is going on with my gmail account. I currently use this script to email the customer a confirmation of his order and the sales people a copy of the order. At 10 pm (give or take), gmail bounced the emails and sent me an email saying that this was spam (mind you, this is only 3 emails sent at a time). When I came in this morning, gmail would not download with Outlook (prompting me for user/pass). When i went to gmail in the browser, it required me to do a captcha. Once I logged in the browser, Outlook started working and the orders started sending email again.

    What is going on with this? How can I correct it?

  65. 65 JENSEN

    phpMyAdmin tried to connect to the MySQL server, and the server rejected the connection. You should check the host, username and password in config.inc.php and make sure that they correspond to the information given by the administrator of the MySQL server.

    how should i counter this

  66. 66 ashok

    hi

    i wroet mail functionality and if i copy and paste images in that teaxt area they are displaying well
    but after sending mail if i checked the mail it comes as a source code

    plese send the solution
    Thanks &regards
    ashok

  1. 1 48 links PHP (perché 50 “fa brutto”) | Napolux.com

Leave a Reply