Send Email from Android and iOS with IonicFramework

Sending email directly from your mobile application might be critical at some point in time.  You may want to create an easy outlet for users to send you feedback about your app without having to sift through your website.  Using the Apache Cordova plugin, Email Composer, you can easily send email from Android and iOS with IonicFramework.

Using a command prompt, navigate to your Ionic project and run the following command:

This will download the Email Composer plugin and install it into your project for use.  As described in the project’s README, to send an email you must use the following function:

Parameter information is as follows:


Parameter Description
callback Function that receives a return parameter from the plugin
subject A string value subject for the email
body A string value email for the email body.  Can be HTML if isHTML is set to true
toRecipients An array of string value email addresses
ccRecipients An array of string value email addresses for the CC
bccRecipients An array of string value email addresses for the BCC
isHTML Boolean determining if the email body will be plain text or HTML
attachments An array of the files, with full paths, that you wish to send
attachmentData An array of file name data pairs

An example of this plugin in action can be seen here:

It is a good idea to note that this will only work on the device.  Plugins cannot be tested from a web browser.  It is also important to note that emails can only be sent if the user has configured a mail client on their device.  If no mail account is found, a popup will be shown stating so.

A video version of this article can be seen below.

Nic Raboy

Nic Raboy is an advocate of modern web and mobile development technologies. He has experience in Java, JavaScript, Golang and a variety of frameworks such as Angular, NativeScript, and Apache Cordova. Nic writes about his development experiences related to making web and mobile development easier to understand.

  • sekhar

    Hi Nic, Nice tutorial thankq very much.
    I’m using ionic for android app development and trying to integrate email plugin.
    I have a question, when I use “ionic serve” the browser giving me errors. to test in emulator its very slow, what is the best way to test and if any errors how to get it in my console from where I triggered ionic serve command?

    Thanks in advance.
    sekhar

    • Hi Sekhar,

      You cannot test Apache Cordova plugins in your browser because they use native device code. The web browser has no idea how to process this device code. If you’re developing for Android, I recommend you try Genymotion as it is like 500% faster than the stock Android simulator. The iOS simulator should be pretty quick already.

      Errors can be tracked via ADB for Android and Xcode for iOS.

      Please let me know if this helps you.

      Cheers,

      • Sekhar

        Hi Nic,
        Thanks for the fast reply and It will help a lot. If possible can you give me the steps how to enable adb to debug my apk that created from ionic.

        Thanks,
        Sekhar

        • With your device plugged in or a simulator running, enter adb logcat into a command prompt, or terminal. That will show you all device or simulator events as they happen, including errors.

          Hope that helps 🙂

          • Sekhar

            Thanks Nic, It worked and I used Genymotion. Thanks for the help.

          • yamini

            hi.. as you suggest i had used adb logcat, but i am not able to check the errors of the particular application an building, the getting entire details of my phone like sim details and so on., like shown in the picture. can you suggest a way to see the errors of my debugging application.
            thanks in advance

          • Finding errors in the logs is difficult because you’re dealing with a mess of text. I cannot help you based on your screenshot, but if you run adb logcat then launch your app, you should see more useful things. The logs change as you do things in your app. So if you’re having trouble sending emails, keep an eye out for a log that occurs during the attempt.

            Regards,

          • krishna

            Hi Nic im krishna and im a fresher i need to ask whether there is any way to send email automatically when we press a button or we need to open the email composer on click of button

          • For the users best interest, Android and iOS do not allow for emails to be sent without opening the composer window.

            If you want to trigger background emails you’ll have to make a web service that the device connects to.

  • Joseph

    Hey Nic!
    I’m looking for a way to have an email be sent at a specific time automatically, do you have a way to do this, without having to set up a server? or just have it send once it connects to the internet?.

    • Hi Joseph,

      For security reasons, you cannot send native background emails on behalf of the user. You have two options for sending emails:

      1. Use the Email Composer to launch the devices native email client and have the user confirm sending
      2. Develop a web API and have your app code trigger a request to it. The web API will send the email, not the device

      It sounds like both of these scenarios are not what you’re looking for. Am I correct?

      Regards,

  • dianikol

    Hi Nic. great tutorial as always!

    Is it possible to expose the email composer with this plugin?

    Thank you.

    • The email composer should always display when using this plugin or any other because Android (and maybe iOS) won’t let you send background emails. It is deemed a security concern by the device operating system.

      Does this answer your question?

      Regards,

      • dianikol

        Yes, you made it clear to me. Thank you very much for your quick response.

        I also want to ask this. I am using phonegao developer app. It won’t work there either, only if i install the app, right??

        Thanks again and sorry for doing multiple questions!!! 😀

        • General rule to plan for is that plugins won’t work anywhere except for a device or emulator.

          Same applies for this plugin as well.

          Cheers,

          • dianikol

            Cool, thanks. Keep up with this kind of posts-tutorials. Great job!

  • Bushra

    Hi Nic, Thank you for your tutorial 🙂
    Can you give me an example about attachmentData
    “An array of file name data pair”
    say I want to send text file …

    Thanks in advanced

    • Well do you want to send the files as base64 data or attachment files? Two very different ways to send files.

      Regards,

  • Enamul Haque

    Hello Nic Roboy,
    Your tutorial is nice . I want to find my imei numbers from ios and android phone.
    1. How to get imei number using ionic framework?
    2. How to send sms to mobile?

    Please Help me…….

    • I only accept tutorial requests via my Twitter. It is inappropriate to ask for things in the comments section of unrelated posts.

      Regards,

  • Jose Rosas

    Hi Nic, awesome work, thanks. Just a question How can I pre-polulate the body of the email with location and other values coming a angular controller? Thanks in advance.

    • I’m not too familiar with geolocation in Apache Cordova, but you would just get the information you need and pass it into the body parameter of the email composer.

      Maybe something like:

      Of course most of what I wrote is psuedocode, but hopefully you can get the idea. Then you would just pass emailBody into the email composer plugin.

      Regards,

      • Jose Rosas

        Thanks Nic, Can I use angular directives such as: emailBody= {{object.name}}?
        Or should this be handled by variables exported to $scope? For example if I have a factory providing me with some information, I could declare $scope.object, and pass it on to the email controller?

        • Sounds like that should be alright. Without seeing your implementation it is hard to tell though.

          Maybe when you’ve drafted something close, put it on GitHub 🙂

          Regards,

  • Edward Soares

    There seems to be a problem with this plugin in particular, it works great yes, however you can not use it in more than one app installed on the same device. It makes android think the same app is already installed if this plugin is in a second app you are trying to install. And yes it is truly a different app with different com.etc and versioning. A fix for this?

  • sooz

    Hi Nic, when I push to send the email with GMAIL it crashes and say: GMAIL was closed.
    why?

    • Sounds like it might be a problem with the actual plugin. You should open an issue ticket for the developer on GitHub describing your problem.

      Regards,

  • sooz

    Hi Nic, I tried your code now its work but when I attached an attachment the app said me that is impossible sent email with that attachment and sent the mail without the attachment. Probably I have mistakes in the code to attached the file… can you help me? I post the code relative to my controller… however I installed the plugin ngCordova file.

    the code is:

    .controller(‘imageController’, function($scope, $cordovaCamera, $cordovaFile) {

    $scope.images = [];

    $scope.addImage = function() {

    // 2

    var options = {

    destinationType : Camera.DestinationType.FILE_URI,

    sourceType : Camera.PictureSourceType.CAMERA, // Camera.PictureSourceType.PHOTOLIBRARY

    allowEdit : false,

    encodingType: Camera.EncodingType.JPEG,

    popoverOptions: CameraPopoverOptions,

    };

    // 3

    $cordovaCamera.getPicture(options).then(function(imageData) {

    // 4

    onImageSuccess(imageData);

    function onImageSuccess(fileURI) {

    createFileEntry(fileURI);

    }

    function createFileEntry(fileURI) {

    window.resolveLocalFileSystemURL(fileURI, copyFile, fail);

    }

    // 5

    function copyFile(fileEntry) {

    var name = fileEntry.fullPath.substr(fileEntry.fullPath.lastIndexOf(‘/’) + 1);

    var newName = makeid() + name;

    window.resolveLocalFileSystemURL(cordova.file.dataDirectory, function(fileSystem2) {

    fileEntry.copyTo(

    fileSystem2,

    newName,

    onCopySuccess,

    fail

    );

    },

    fail);

    }

    // 6

    function onCopySuccess(entry) {

    $scope.$apply(function () {

    $scope.images.push(entry.nativeURL);

    });

    }

    function fail(error) {

    console.log(“fail: ” + error.code);

    }

    function makeid() {

    var text = “”;

    var possible = “ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789”;

    for (var i=0; i < 5; i++) {

    text += possible.charAt(Math.floor(Math.random() * possible.length));

    }

    return text;

    }

    }, function(err) {

    console.log(err);

    });

    }

    $scope.urlForImage = function(imageName) {

    var name = imageName.substr(imageName.lastIndexOf(‘/’) + 1);

    var trueOrigin = cordova.file.dataDirectory + name;

    return trueOrigin;

    }

    $scope.sendEmail = function() {

    if(window.plugins && window.plugins.emailComposer) {

    }

    });

  • Dan

    Dude, you rock. All of your blog tutorials are spot on and to the point. I’ve used several including this one and you’re doing a great service to the Ionic community. Keep it going!

    • Thanks for the compliment! Always happy to help fellow developers 🙂

  • John Read
  • Ace John Avila

    Hi Nic Thanks to this tutorial it helps me to start my student’s email module. Do you have tutorial for inserting attachment in email?

    • I don’t have a tutorial for this, but this plugin supports files or base64 data.

      Regards,

      • Ace John Avila

        Thank you again. =) keep it up for helping us. You’re so kind.

  • Madley

    Hi Nic, thanks for the great tutorials!

    I’m having a hard time with incorporating an attachment.

    I’d like to attach a text file (CSV) as Base64, but I must be doing something incorrectly. Can you show me the correct way to do this? Any help is appreciated, thanks!

    var testAttachment = “data:text/csv;base64,[blah blah blah]”;

    };

    • I assume [blah blah blah] is already base64 format data? If so, try removing everything that comes before it.

      Otherwise what problems are you running into?

      Regards,

  • Diego R Castillo Rios

    Hi, I’m getting an error when I try the plugin in iOS 9.0: MailCompositionService quit unexpectedly.

    This is what I get in the console:

    weMobile[2948:44081] viewServiceDidTerminateWithError: Error Domain=_UIViewServiceInterfaceErrorDomain Code=3 “(null)” UserInfo={Message=Service Connection Interrupted}
    weMobile[2948:44081] Response -> 0
    weMobile[2948:44081] ****************************AVVIATO

    Does anyone here get the same issue and if so, does anyone have a workaround for this? It seems to be working fine in iOS 8.4.

    Thanks a lot!

    • You should raise an issue ticket with the plugin developer. If it works in iOS 8, but not 9, I don’t think we’re going to be able to do anything without touching the plugin itself.

  • Jim Bakoume

    I created a personalized form with all the fields I wanted then below I added a button below wish wil be used by the user to send the form. but I don’t know how to configure the button to make it send the form when a user clics on it. I need help for that.

    • What are your intentions with the form? You cannot send emails from your device outside the native email client.

      • Jonatan Scaglia

        Hello, I am trying to send mail to the fields of a form, but I’m not getting the emails.
        I’m using the code provided by the official website of ngCordova
        Can you help me? This is my code with a fake mail but really I’m using actual mail.
        Thanks!!

        $scope.enviarPedido = function(){
        $cordovaEmailComposer.isAvailable().then(function() {
        // is available
        }, function () {
        // not available
        });

        var email = {
        to: ‘[email protected]’,
        cc: ‘[email protected]’,
        bcc: [‘[email protected]’, ‘[email protected]’],
        subject: ‘Cordova Icons’,
        body: ‘How are you? Nice greetings from Leipzig’,
        isHtml: true
        };

        $cordovaEmailComposer.open(email).then(null, function () {
        // user cancelled email
        });
        };

          • Jonatan Scaglia

            sorry, my bad 😉

          • More logs, less code 😉

          • Jonatan Scaglia

            that’s the problem, I have no logs 🙁

            I am testing a Windows Phone device and click the button does nothing, either ionic strip console error and not allow me to run the run so I have to do it from visual studio.

            If you got any documentation you can read to get the problem I’d appreciate it. I did not quite understand what you meant by that I must be associated with my native mail.

            regards

          • I don’t think Windows Phone is supported with Ionic Framework. If the plugin is supported, you’ll need a mail account on your phone. The plugin only pre-fills an email in your default mail client. Without a mail client and without a mail account, this cannot happen.

            My guess is your simulator doesn’t have a mail account or a mail client. Most simulators do not.

  • Nirmala

    Hi to all,
    I need to send a notification as email to the user about the User details using Ionic.Is it possible

    • I’m not sure what you’re asking. Can you try again with full details?

      Best,

    • Jomel Barbadillo

      same problem haha! PUSH NOTIFICATION : (

  • Siddhesh
  • rejinthala manoj

    Hi Nic, am developing one application with ionic i get the data from the service i=and i display the data to the user .user can share the data via email as well as facebook.when user share via email the content from service should share as a pdf.so i created pdf and i used ngcordova file i attach created file to the email it works great in android but in ios the attachment is missing i gave document path to store the pdf

    • What do your logs say? Are you sure you had the correct path?

  • Jomel Barbadillo

    As always, You bring nothing but the best tutorials ever. I was wondering if you have created a email notification. Thanks sir!

    • What do you mean, email notification?

      • Jomel Barbadillo

        When you sent an email to following users. Then the users will receive a notification on it. “You receive an email from [name]” then if you replied they will notice it.

        • Sorry to say this, but I still really don’t know what you mean. Can you give me actual examples?

          • Jomel Barbadillo

            Sorry! just took me alot of time to figured out.

  • Mounika

    Hi NIC,
    i am new to ionic,when sending email with large attachment more than 15mb in ios devices my app getting stuck.could you please suggest me

    • Don’t send 15mb attachments in a mobile app. That is too much.

  • Robert Gardner

    Nic, I’m trying to get your sample to work on my iPhone 6. I’ve triple checked line by line and it’s exactly how you presented it in the video. I’ve attached screen snips of the code and the resultant display on the phone. The “Send Mail” button displays briefly upon app launch but then goes away… Any assistance / thoughts would be greatly appreciated. I’ll disclose that I’m farily new at this but thought the example would run out of the box… I also thought that even though the code won’t launch a browser email client I thought it would display a message… I do a build.phonegap and successfully get it installed on my phone same results as the ionic serve simulator.

  • Duncan Underwood

    testing the button on my ios device. pressing the button and nothing happens. cant work out why

  • Ace John Avila

    Hi Nic. I used your plugin to my application in Ionic framework. My problem is whenever I sent an email my application shows blank page or automatically logout. I already used $state.go(‘tabs.emails’, {}, {reload: true}); in my email returncallback to go back to my email module but the same problem I encountered. What do I need? Thanks to your response =)

    • Does the email send? Your description is very confusing and I don’t really know what you’re trying to say.

      • Ace John Avila

        My bad Nic. Sorry if you got confused to my question, Anyways I solved my problem now. I just need to uncheck the Don’t Keep Activities on Developers options. Thank You!

  • Fred

    Nic, Thanks for the tutorial. I cannot get it to run.
    here is my code running on IOS device IOS 9.
    Thanks

    if(window.plugins && window.plugins.emailComposer) {

    this is the Log
    2016-03-02 17:10:47.178 TimeKeeper[9173:4453530] ****************************AVVIATO

    2016-03-02 17:10:47.183 TimeKeeper[9173:4453530] ERROR: Method ‘showEmailComposer:’ not defined in Plugin ‘EmailComposer’

    2016-03-02 17:10:47.183 TimeKeeper[9173:4453530] -[CDVCommandQueue executePending] [Line 159] FAILED pluginJSON = [“INVALID”,”EmailComposer”,”showEmailComposer”,[{“subject”:”Feedback for your App”,”toRecipients”:[“[email protected]”]}]]

    • The official docs don’t indicate a change:

      https://github.com/jcjee/email-composer

      Can you confirm that you’re not trying to use Ionic Serve or similar? That you’re building and then installing to the device or simulator?

      Best,

  • Christianne Yu

    hi, thanks for the tutorial. but my app doesnt work yet, what do you put at the controller.js?

    • I’m not sure what you’re talking about. Can I get more information?

  • Bob G.

    Could you share with me how to pass data from 2 input separate select statements within my index.html as variables to the email plugin. ie. I want to build custom subject and body information using variables. Thanks..

    • You’ll have to use ng-model on your form elements. That offers two way data binding between the UI and your controller. Then you can pass it into your email function.

      Best,

      • Bob G.

        I already have ng-model on those form elements. I don’t know how to code on the email function side to access them.

      • Bob G.

        Hi Nic, I’m not sure if i posted my response to your suggestion but I already have ng-model included. My dilemma is that I don’t know how to code the plugin within the controller (it’s pretty much verbatim using your example . I’m able to hard code a variable within the plugin (var somevalue = ‘example value’ ) and then use it to concatenate within the plugin. I did this to validate I could use variables within the plugin. I now need to use the selected input from the index.html and pass it to the email plugin. Works fine, launches native email function just fine with the hard coded values inclusive of concatenated subject string.

        I’ve done lots of research and tested lots of combinations using $scope but I can’t seem to get the right combination or placement of the proper code to make it work. Since there are actually 2 item-selects I’m also not clear on how to distinguish them within the controller. Would the ng-models be dot notation such as alldata.tt_AircraftId alldata.tt_CrewMsg so I could id them or simply as noted in my current ng-model. I just can’t get any traction on this last issue. Any assistance is greatly appreciated.

        https://uploads.disquscdn.com/images/af0de9be404ab3895a770a964e85588d6efe52cfc5a3dfd353055a9513e6520f.png

        https://uploads.disquscdn.com/images/09839bc798c6b52a0f91cbad586c866953a330c408cbca50f9ba5722f20c5775.png

  • siddharth

    Hello Raboy , thanks for your tutorials ..its really helpful to freshers like me…I just want to know one thing regarding email functionality , That is it possible to trigger email in background without any user interaction in ionic.?

  • Bhanuka Samarasinghe

    Hi I used ionic creator to create my app! I tried you example in an app which is not created from the ionic creator and it worked really well! For projects which I’m creating from the ionic creator I don;t know where put this ng-controller and ng-click event is not working here! I attached two photos which are sample apps I created with and without the ionic creator!

  • Bhanuka Samarasinghe

    Hi I used ionic creator to create my app! I tried you example in an app which is not created from the ionic creator and it worked really well! For projects which I’m creating from the ionic creator I don;t know where put this ng-controller and ng-click event is not working here! I attached two photos which are sample apps I created with and without the ionic creator!!!

    • I don’t use Ionic Creator so I don’t know.

      Sorry,

      • Bhanuka Samarasinghe

        No worries! I solved it 🙂 Thank you for your kind reply 🙂

        • Kasim Sheyi

          pls i created my app with the ionic creator guess thats why the tutorial didnt work for me…please can you assist me to make it work for me

          • Bhanuka Samarasinghe

            So what is your problem?
            What are the errors?

          • Kasim Sheyi

            well when i hit d Send button according to how u did it in the tutorial no mail app came up

          • Do you have an email client installed? What do your logs say?

          • Kasim Sheyi

            yea i have email client but no log errors

          • How are you checking your logs?

  • Sereyvuth

    Why like this.
    Can you solve it?

  • Sereyvuth

    Can you solve it?

    • skTzoOoTech

      You probably are using a newer version of corodova. Go to https://cordova.apache.org/plugins/ and check the syntax on how to add the plugin. The error obviously is saying it can’t find the plugin on that address anymore. Copy the git URL you used and try it on a browser and see for yourself.

  • mahaboob baig

    Hi Nic, This code in not working in android. I am testing on android device.
    This is my code.
    $scope.sendMain(){
    if (window.plugins && window.plugins.emailComposer) {
    window.plugins.emailComposer.showEmailComposerWithCallback(function (result) {
    alert(result);
    },
    “This is for testing”, // Subject
    “Hello mahaboob”, // Body
    [“[email protected]”], // To
    null, // CC
    null, // BCC
    false, // isHTML
    null, // Attachments
    null); // Attachment Data
    }
    }
    Help me where i am wrong. Thanks

  • Toshiketsu Kaku

    Hi,

    Thanks for your tutorial.
    The code works to me, but when i try to send attachment, i can’t.

    Can you give me a sample of how attachment being sent?

    Many Thanks,
    Clarence

    • When you say can’t, can you be more specific? Does it crash your app? Do you get errors? Is the file not right when received?

      Please provide more details including logs, even if there are no errors.

      Best,

      • Toshiketsu Kaku

        Hi,

        Here is my code:
        $cordovaFile.checkFile(cordova.file.dataDirectory, ‘myFile.txt’)
        .then(function(success) {

        ==================================
        When the checkFile() returned success, and it opened the email composer. However, no attachment in the email. I am not sure where went wrong. 🙁

        • Have you validated that the paths are correct? Maybe print out the following and see what you get:

          Best,

          • Toshiketsu Kaku

            Sure.. will do that.
            Anyway, may i know what’s the difference between “attachment” and “attachment data”?
            when we want to attach a file, do we need to fill in both parameters?

          • Use one or the other. One takes a path to the file and the other takes base64 file data

          • Toshiketsu Kaku

            Noted. Thanks Nic!!

          • Nicholas Richardson

            Did you ever get attaching the file to work? Having the same issue as you described myself.

  • Sean Yap

    Hi man, I have an issue. I followed your codes exactly, but I still cannot get the email to work. Every time I install it on my Android phone, and press the ‘Send mail’ button, nothing happens at all. Attached is my coding, I would appreciate it if you were to take a look. Sorry, I’m really not experienced with Ionic.

  • Sean Yap

    Hi man, thank you so much for this. You can’t believe how helpful this is to me.

  • Пётр Кропо́ткин

    Thanks for the tutorial, works great for me except for the callback part. It doesn’t execute. I tried changing it to a named function, placed it in several parts of the if block and promise I’m returning but no luck. I saw your newest tutorial using Mailgun but I prefer this method. Any pointer is appreciated

  • Hasani Girod

    Hi Nic,
    I am trying to attach a pdf, the pdf is already in base64 format.. see code below

    var attachData= [
    [‘test.pdf’,data]

    but when it runs on the actual device i keep getting an error” cannot attach empty file”
    Do you have any idea of the problem here??

    • It looks correct to me. You might want to raise a ticket with the plugin developer

      • Hasani Girod

        ok thanks

  • Gail

    Thanks for the video. I’m stuck at the point when I’m supposed to run: adb install -r platforms/android/ant-build/ExampleProject-debug.apk. I get adb ‘command not found’. Is adb the Android debug Bridge? Any good instructions around for installing that (just tried a couple of tutorials and nothing worked so far.) Thanks. -GP
    Update: I found the adb.exe was already installed, added it to the system path, then it was found.

  • Hey Nic, I am a big fan of your tutorials, your are doing fantastic work. I am having a strange bug when I test on both my native iOS device as well as the emulator, where the plugin only seems to work when I close the app and re-enter. This happens with my PDF viewer as well where I use cordova’s inAppBrowser plugin. Have you ever encountererd anything like this? Thanks much in advance.

  • karthik kumar

    is ng-repeat possible in the body

    • If you need to loop over something, you should probably construct your body before trying to call the method.

  • tanveer

    not working

  • tanveer

    $scope.sendFeedback= function() {
    console.log(‘function is running’);
    if(window.plugins && window.plugins.emailComposer) {
    window.plugins.emailComposer.showEmailComposerWithCallback(function(result) {
    console.log(“Response -> ” + result);
    },
    “Feedback for your App”, // Subject
    “”, // Body
    [“[email protected]”], // To
    null, // CC
    null, // BCC
    false, // isHTML
    null, // Attachments
    null); // Attachment Data
    }
    }

  • tanveer

    how to send email plz guide me

  • Yogesh Yadav

    hi,
    I am facing an issue with the tabs while using this plugin, when the application regains focus after sending email. The tabs get blank/disappear.

  • Gaston Elordi

    Nice tutorial!
    Could you share some email clients to use on android?
    Does gmail app work?