[go: up one dir, main page]
More Web Proxy on the site http://driver.im/

Send Text Messages with PHP

By  on  
Text Message

Kids these days, I tell ya.  All they care about is the technology.  The video games.  The bottled water.  Oh, and the texting, always the texting.  Back in my day, all we had was...OK, I had all of these things too.  But I still don't get the volume of texts that I hear my younger female cousins send.  Thousands and thousands of them each month.  WTF are all of these texts for?  Here's a thought:

omg did you hear?

no wut

omg i can't believe you didn't hear

lol tell me!

jenny and mark were holding hands

omfg does john no?

ok i made it up, ur so lame

Riveting.  Jokes aside, text messaging can be an extremely useful way to get out of calling that person you hate calling communicate quickly and efficiently.  Many websites are now offering text message notifications instead of email notifications, which can be nice in the case of time-sensitive information.  After a bit of research, I found out how easy it was so send text messages using PHP, so that I can integrate text messaging into my apps!  Let me show you how!

The Methodology

Unbeknownst to me, sending text messages can be as easy as sendmail, because you can send your text to an email address and it will be delivered.  There are two pieces of information you must know:  the phone number and the carrier's text message email domain.  Needing to know the recipient's carrier is not ideal, but necessary.  Luckily Kevin Jensen has compiled a list of carriers and domains:

Phone companies have internal lookups for phone carriers but developers like you and I don't get access to them, so knowing the carrier is  a must.  To send a text message, you email {phoneNumber}@{carrierDomain}.

The PHP

PHP's provided method for sending emails is the mail function.  Its usage is quite simple:

bool mail ( string $to , string $subject , string $message [, string $additional_headers [, string $additional_parameters ]] )

Using the mail function and the text message email format, sending a text message is as easy as:

// Call Jenny
mail("5558675309@txt.att.net", "", "Your packaged has arrived!", "From: David Walsh <david@davidwalsh.name>\r\n");

Note that no subject line is provided, and more importantly, a FROM header is within the last parameter so that the recipient knows where the text message has been sent from.

Who knew it was that easy?  I always assumed text messaging had its own protocol and all that magic.  Apparently not!  Spend a few minutes playing around with text messaging yourself;  it's one of those things that's both neat to do and useful!

Recent Features

  • By
    Chris Coyier&#8217;s Favorite CodePen Demos

    David asked me if I'd be up for a guest post picking out some of my favorite Pens from CodePen. A daunting task! There are so many! I managed to pick a few though that have blown me away over the past few months. If you...

  • By
    How to Create a RetroPie on Raspberry Pi &#8211; Graphical Guide

    Today we get to play amazing games on our super powered game consoles, PCs, VR headsets, and even mobile devices.  While I enjoy playing new games these days, I do long for the retro gaming systems I had when I was a kid: the original Nintendo...

Incredible Demos

  • By
    JavaScript Battery API

    Mozilla Aurora 11 was recently released with a bevy of new features. One of those great new features is their initial implementation of the Battery Status API. This simple API provides you information about the battery's current charge level, its...

  • By
    CSS Selection Styling

    The goal of CSS is to allow styling of content and structure within a web page.  We all know that, right?  As CSS revisions arrive, we're provided more opportunity to control.  One of the little known styling option available within the browser is text selection styling.

Discussion

  1. Good article David. I will be definitely be using this information.

  2. If you find this intriguing, you should look at Twilio. It’s pretty freakin’ awesome and you can do quite a bit with SMS and even send/receive phone calls programmatically.

    • Andrew Hart

      Agreed – I implemented twilio for one of our upcoming features for an app i’m working on involves the option to receive SMS instead of Push notifications in case the user is in an area where data is limited or unavailable. It is uber easy to integrate and works flawlessly :)

      Ironically David I have actually texted people using email in the past but never thought about using it in a web application lol –

      nice article, thanks again.

  3. Anyone get this working on any uk networks?

    • I didn’t have a way to test UK networks. I did text myself (as you can see with the screenshot above) with the following phone format:

      ###-###-####

      You may need to add the leading zero or country code.

    • Ian

      Unfortunately this method doesn’t work in the UK and probably only works in the US and a handful of other countries. This is because mobile operators in the UK don’t give us email addresses that send to people as texts, certainly not with the mobile number as the address. It’s a big shame as you basically have to sign up for expensive sms gateways.

  4. Thanks for posting, David. Your humor (especially the texting banter) almost had me on the floor.

    Any chance someone has this as a csv or possibly in a mysql table for lookup from a form field? That would be nice.

    I did set this up once awhile back for a client that wanted a text message when someone filled out her contact form requesting a meeting. Kinda one of those aha moments at the time. Only one number and one carrier though. Might have to look into Twilio for more complex implementations.

  5. This is very carrier dependant. Some carriers do not allow this, and others make this low priority, sometimes resulting in messages being late, or never delivered.

    Regardless, there are the formats for the big 4:
    Sprint phonenumber@messaging.sprintpcs.com
    Verizon phonenumber@vtext.com
    T-Mobile phonenumber@tmomail.net
    AT&T phonenumber@txt.att.net

  6. Alex

    Any carrier information for Greece?

  7. David Myers

    I’ve done this before and I have a tip to eliminate some issues I’ve encountered with this method.

    The first issue is that this requires the user to specify a carrier which can be annoying and even put some people off of the concept. The second issue is that using the mail function opens a socket every time it is called, so doing mass texts becomes a very big issue very fast.

    To get around the first issue, you just have an array of the carrier mail servers {@vtext.com, @txt.att.net, etc} and then you just append the users cell number to the beginning of each array value when you want to send a message. To do this you have to build up an array with all of the possible carriers, but a quick wikipedia search makes this a simple task.

    Now to deal with the volume issue you can just use the PEAR mail function (commonly installed along with PHP). Doing this, you can send one message to multiple addresses at the same time while only using one socket. This also allows you to send the message to every possible phone number/address very quickly. The message will only go through to the correct address and you don’t have to know who the carrier is.

    As a side note, some carriers don’t interpret the FROM email headers correctly/uniformly so it’s something you definitely want to test if at all possible.

    • Chris McKee

      Seems like a good concept (even if theres no guarantee of delivery).
      Doesn’t seem to work with O2 in the UK, which is sucky.

    • David Myers

      Yeah, unfortunately, without an SMS gateway, it’s extremely difficult to test across carriers and there’s no real guarantee of delivery. Very handy for smaller projects though.

  8. David Myers

    Aaaand that didn’t format my text. Sorry for the unreadable wall of text, haha.

  9. Bastien

    I would urge caution here. From hard won experience, not all carriers will treat the sending of an email as text. Some might, some will send it as emails depending on the users data/email plan. Others simply won’t deliver the message at all

    For truly reliable text messages, you will need an SMS gateway provider, twilio is a great example of this and they are easy to integrate into the site but it will cost. There are various free gateways, with varying degrees of successful delivery.

  10. crocodile2u

    omg i can’t believe i didn’t hear about this before!

  11. Whats e the cursing!?!!

  12. Great article David.

    I’m also sharing a list of email-to-SMS gateway providers as a .SQL and .CSV file at: http://www.uptimerobot.com/sms.asp (check the bottom of the article).

    This is a regularly updated list as some gateways become valid/invalid from time-to-time and it includes the prefixes/suffixes for them as well.

    Hope it helps.

  13. I’ve played with this a bunch, and have several friends in the phone industry.

    The email to SMS priority seems low on some carriers, what’s more, depending on the plan & carrier, there are additional steps or even FEES for this.

    Fido (Canada) can/used to charge up to $0.50 per message.
    They also require the user to respond to a generic message with “READ” in order to download the remaining part(s) of the message. Not fantastic.

    SMS Gateways are fairly inexpensive for a business sending messages. Individuals probably don’t want to pay the prices.

  14. Excellent article. I’ll try to find the carrier information for Portugal :D

  15. Oops. I didn’t know I have to insert <br/> to make linebreaks…

  16. I’ve been using email to SMS gateways for years now. Here is a good list of SMS gateways around the world, https://secure.wikimedia.org/wikipedia/en/wiki/List_of_SMS_gateways.

    I agree though that one needs to keep in mind a lot of carriers/mobile phones do not support the subject line or from field. What I do is is add something to the SMS message to identify who the sender is.

  17. I have been doing sms’ing in the US for a little while and one big requirement that hasn’t been mentioned is that for some carriers you have to a reverse-lookup(able) domain. So if your mail() function sends your email from a domain that is not your mail server you must make sure the lookup will return your mailing server.

  18. Any one know if providers in India support this ? I have a hunch this won’t work with Indian providers.

  19. Ian

    Years from now, when you and your lovely wife have a daughter, you’ll look back at this post and laugh.

    But thanks for this tutorial, my friend and I are making a support system for teens who have been out partying, and this will be an invaluable resource.

  20. i use the google voice unofficial api for this , which means i dont need this mail function availible

  21. Where can I find email id for sending sms to Indian numbers? Mumbai, especially.

  22. Callum

    Hey guys just a heads up, this only works in a couple of countries other than the US because those countries CHARGE USERS FOR RECEIVING AN SMS. Many countries do not! So if you’re looking into this trying to find your gateway you probably won’t unless your in a country that charges to receive a text message.

    • Ian

      Thanks Callum. I hadn’t realised this. Do people really have to pay to receive texts in the US? How about sending? Doesn’t sound like a good deal if that’s the case.

  23. Really useful, particularly the link to all the providers.

    Cheers fo posting!

  24. I created a simple function that makes it easy for app developers to notify users via a text. Here’s the link: http://forrst.com/posts/PHP_Function_to_Send_Text_Message-zlg Or look at this:

    function send_text_msg( $number , $carrier , $subject , $message )
    {
    global $setting;

    $carrier_list = Array(
    'att' => 'txt.att.net',
    'verizon' => 'vtext.com',
    'tmobile' => 'tmomail.net',
    'sprint' => 'messaging.sprintpcs.com',
    'nextel' => 'messaging.nextel.com'
    );

    return mail( $number.'@'.$carrier_list[$carrier] , $subject , $message , "From: ".$setting['company']." ");
    }

    // Send it
    send_text_msg( '5551234567' , 'verizon' , 'New Notification!' , 'Jim has updated your project. Go ahead and login to see the changes made.' );

  25. iQhry

    it won’t work on SMART phone numbers. i tried and tested it but it really don’t work..i’m currently in Philippines.

    • soulmenj

      i’m trying to solved this kind of problem as well :) you might want to share your ideas if you have solved this problem :) lol.

      i’m from Philippines too. I want to developed small site that offer text message like this site. magtxt[dot]com if you happen to visit this site.

      cheers!

  26. Hi,
    Just wanted to say the script works here in South Africa (MTN).

    Just substitute the AT&T with the cell number in xxxxxxxxxx@sms.co.za

    It’s free but it can take up to an hour to get through.

    Cheers,
    Carl.

  27. After seeing this post I was considering writing a script to integrate into a CMS for the purposes of verifying people. I ended up deciding not to follow through with the idea, but I’d like to share some code that I came up with so that it wasn’t a complete waste of time.

    What I wrote are 2 files. The first file contains a form where you select your mobile carrier from a drop-down list, then you enter your mobile phone number into a text field and hit submit. This sends the data via POST to the second file which will use the carrier and number data to try to send a message using the SMS Gateway.

    I didn’t complete all of the global carrier options for the drop down selection area, but I did finish entering in American and Canadian providers. If anyone wants to take this file and either finish it or re-purpose it, you have my blessing.

    Download zip: http://www.filedropper.com/mobile_2
    Pastebin form.php: http://pastebin.com/4Fqh7YJR
    Pastebin text.php: http://pastebin.com/WHkUrSLh

    • Brian

      Eric, thank you for your contribution (the filedropper link doesn’t work anymore, fyi). Can I use some/all/edited version of your code?

  28. charley hankins

    That’s all very well and good. However, when a person starts receiving harassing texts from an anonymous source, that is not cool. And there appears to be no way to trace where the call is coming from. We have called AT&T and filed police reports. If you would like to help, please discover a means of tracing them.

  29. Thanks,

    Can we use this SMS method in India…..

  30. Can this be used in South American countries? Has anyone on here set texting up for there?

  31. Michael

    Does it applicable in Malaysia carrier ?

  32. Prabu

    I need to send sms to spain mobile? Please share the correct email address.

  33. Nice post..does anyone know anything for nigerian carriers?

  34. Simon Alison

    This is great – and it works just fine with O2 in the UK!

    S

  35. shakhawat

    I need to send sms to Bangladesh mobile? plz anyone help me.

  36. Liam

    You can always use an international bulk SMS provider, for example; http://www.sourcesms.com

  37. elangovan

    hi, i want to script for php mail function.my mail id is end with .net(eg:hr@icdipl1.net).can you help how to send tiss mail di?

  38. Terry Wysocki

    Has anyone got this to work on Verizon in the US? If so, what’s the syntax? I can’t get it to work with
    mail("16265551234@vtext.com", "", "This is the message text", "From: Tester\r\n");
    Does the “from” address have to be a real address and from the sending site?

  39. Awesome tutorial, am going to implement it on my new website. Thank you..

  40. James Tellerton

    Hi,
    Using this code:

    mail(“1231231231@vtext.com”, “”, “This is the message text”, “From: jamestellerton@yahoo.com\r\n”);

    The text message arrives at the phone, but the From is not James Tellerton. Instead it is the name of the hosting account that the PHP is running on. Any ideas how to make the From work as intended?

  41. ongpang

    Hello everybody,
    I want to send sms to Cambodia? please help me…

  42. Can you also recieve replies?

  43. Chunks

    Guys do you know which email carrier is valid in philipinnes?

  44. MMortal

    Hi I am pulling the contacts from a MySQL database along with the contact_id. I would like to include a direct link to the text that links back to a delete_contact.php file. What I am not sure is how to pass the variable to the text message and then have it pass it back to the delete_contact.php file. I am familiar with sql and getting better with mysql but need some pointers in php.

    Any help would be great if not I can figure it out, but really appreciate your site it has helped out a lot.

  45. RJ

    “Parse error: syntax error, unexpected ‘$message’ (T_VARIABLE) in D:\wamp\www\smsTest.php on line 3”

    What makes the $message unexpected?

  46. You can find out the email to send to by sending a text to an email address from your phone then looking at the from field.

  47. Thanks David .. I was looking for a simple way to send SMS using PHP

    thank you so much

  48. hey Dave, to do this righteous you’d need a Kannel SMS Gateway. this approach will fail most of the times, as for worldwide developers.

  49. I am kiruba.I did not get one output in chat.if we give the username and message it will not display on the window.only display the username.i give a select query for this.

    <?php 
    session_start();
    include('connect.php');
    print_r($_SESSION);
    if(isset($_SESSION['username']))
    {
    	//echo $_SESSION['username']= 'username';
    	echo $username=$_SESSION['username'];
      $id=$_SESSION['user_id'];
    //$msg=$_POST['message'];
     //$query = mysql_query("SELECT 'user_id' FROM tbl_message,tbl_users WHERE  'user_id' ='.$id.'");
    //echo $query;
    $query=mysql_query("SELECT 'user_id' FROM tbl_message, tbl_users WHERE 'user_id' = '.$id.'");
    
    while($row = mysql_fetch_array($query))
    {
    	echo "$row[username]:$row[message]";
    	
    }
    }
    
    ?>
    
  50. jq

    Be nice if there was a way to make the FROM a Cell-Number so you can begin responding via TXT

  51. Brian Woodward

    Great, but how do you send an image with the text?

  52. ohh this is very good opportunity email to send text msg on mobile i am also looking this feature for my website ypages.pk

  53. hi David!
    thanks for pointing this out!
    could you please update the pdf with these gateways Wayne pointed to in the comments?
    http://martinfitzpatrick.name/list-of-email-to-sms-gateways/

    KR
    Guenther

  54. will this work in any network irrespective to country??

  55. For mexico Telcel? :(

  56. Klaus Donnert

    The biggest problem with email to sms is that both email and sms are low priority network traffic. Sometimes the delay can be 30 minutes to deliver email to sms messages, or the message may be dropped altogether. Twilio (sms to sms over web via their api) is a better choice at US $0.0075(as of this writing) per message. Even Twilio can sometimes be delayed several minutes, but not like email to sms.

  57. Faysal

    Can anyone please provide me Bangladesh Cellular networks Email to SMS Gateway??

  58. I have been doing SMS ing in the US for a little while and one big requirement that hasn’t been mentioned is that for some carriers you have to a reverse-lookup(able) domain. So if your mail() function sends your email from a domain that is not your mail server you must make sure the lookup will return your mailing server.

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!