How to send an email in Ionic framework application?

profile for Nikola at Stack Overflow, Q&A for professional and enthusiast programmers
I’m a big fan of Stack Overflow and I tend to contribute regularly (am currently in the top 0.X%). In this category (stackoverflow) of posts, I will be posting my top rated questions and answers. This, btw, is allowed as explained in the meta thread here.

As you may know, I’m really into Ionic framework lately and am helping out on StackOverflow with the knowledge I gained so far with the framework. I’m in the top All time answerers list.

I answered this question by user varun:

I have a simple page with 3 textbox and a button like this.

<input type="text" ng-model="name" required >
<input type="text" ng-model="city" required >
<input type="text" ng-model="country" required >

<button class="button button-block button-royal ExploreBtn" ng-click="sendMail();">
Send mail               
</button>

Help me , How to send mail with value in first text-field as subject and other two as body in angular js/ionic.

My answer was rather elaborate:

So, basically the comments to your question are correct – you can’t do this purely in JavaScript, you need to use a backend service for it.

Now, what you would do in your sendMail function is call the service by using Angulars’ $httpservice. You can learn more about $http service from the official documentation.

The call would, for example look like this:

$http({
    method: 'POST',
    url: 'http://your.server.com/sendmail.php',
    data: { mailTo: '[email protected]', msg: 'hello!' }
}).then(function successCallback(response) {
    alert("msg sent!");
}, function errorCallback(response) {
    alert("error with sending a msg");
});

Here you have two important parts:

  • url – where is your service (which will finally send the email) located
  • data – what are you sending to this service endpoint

In my example I’ve put the service url to be sendmail.php which, in end, would be written in PHP. I have to stress out that your backend service can be written in any server-side language you’re familiar with (if you’ll research this topic further make sure you read about the RESTful services).

For the sake of this example, the PHP script (unsecured and just for reference) which uses the mail function to send an email would look something like this:

<?php

$to = $_POST["emailTo"];
$msg = $_POST["msg"];

mail($to, "Some test subject", $msg);

?>

Hope this helps clear the confusion.

https://twitter.com/HitmanHR/status/679287774650998785

Written by Nikola Brežnjak