Saturday, June 22, 2013

How to Send an email in a SharePoint Hosted app?

How to Send an Email in a SharePoint Hosted app?

We can send email to the Users / Group in SharePoint Hosted app by using workflow Email Activity.
In SharePoint 2013 Online there aren't any API's available to send email, so to send email in Office 365 online, we'll have to do the following,

While Creating SharePoint Hosted app In Visual Studio, Create a site workflow, after that from the toolbox add the "Email" Activity to workflow,




This activity requires, "TO", "Subject" and "Body" arguments. 
Now we'll create the three arguments of the workflow, we'll pass these arguments when we'll start the workflow.

Now you'll need to provide activity arguments, Body and Subject arguments are simple you can just pass the argBody and argSubj workflow arguments as is, 


but for TO field you'll have to covert the string argTOEmail into Collection,


We'll create a new Collection object of type string.



add this to create the Email collection,


 new System.Collections.ObjectModel.Collection<string>() { argTOEmail }  

our workflow is now complete, 
We'll start our email workflow using JavaScript Object Model.  Include the following code snippet in your app.js file,


 
var context = null;
var web;
var wfManager;
var subscription;
var params;
var _wss;
var argSubj;
var argBody;
var argTOEmail;
function send(Subject, Body, ToEmail) {  
   context = SP.ClientContext.get_current();  
   web = context.get_web();  
   argSubj = Subject;  
   argBody = Body;  
   argTOEmail = ToEmail;  
   wfManager = new SP.WorkflowServices.WorkflowServicesManager.newObject(context, web);  
   context.load(wfManager);  
   context.executeQueryAsync(initWorkflowSubScriptionService);  
 }  

The above code will load the Workflowmanager and on-success will call  initWorkflowSubScriptionService function.

initWorkflowSubScriptionService will start the workflow, and hence will send the email,

 function initWorkflowSubScriptionService() {  
   _wss = wfManager.getWorkflowSubscriptionService();  
   context.load(_wss);  
   context.executeQueryAsync(  
     function (sender, args) {  
       subscription = _wss.getSubscription("f248e55e-495c-4c9b-b4de-618033d6be3b");  
       params = new Object();  
       params["argSubj"] = argSubj;  
       params["argBody"] = argBody;  
       params["argTOEmail"] = argTOEmail;  
       context.executeQueryAsync(  
         function (sender, args) {  
           wfManager.getWorkflowInstanceService().startWorkflow(subscription, params);  
           context.executeQueryAsync(  
             function (sender, args) {  
             },  
             function (sender, args) {  
               console.log("Something went wrong in starting workflow: " + args.get_message() + '\n' + args.get_stackTrace());  
             }  
           )  
         }  
       )  
     },  
       function (sender, args) {  
         console.log("Something went wrong in starting workflow: " + args.get_message() + '\n' + args.get_stackTrace());  
       }  
     );  
 }  

So now you'll just need to call the function send like this 
send ("This is Subject","This is body","test@test.onmicrosoft.com");

There are however some restrictions, 
You can send email only to the Current Domain users.
and using the above approach you can only send email to only one recipient,  
I'll write another blog post on how to send Email to Multiple recipient in SharePoint Hosted app using workflow and Javascript Object Model

22 comments:

  1. Hi,

    What do you replace 'f248e55e-495c-4c9b-b4de-618033d6be3b' with after you created the workflow in project? At least, I can't find my workflow's subscription ID.

    Sorry for the easy question, new to SharePoint here.

    ReplyDelete
  2. In your workflow folder, you'll see SharePointProjectItem.spdata file, in that file you 'll see various Id's. in that you'll see this key
    WorkflowAssociationManualStart.Id


    ReplyDelete
  3. I am trying to send email from my sharepoint hosted app using the workflow as you have shown in your example.
    code not showing any error but not sending mails either can you please help me finding the reason .

    ReplyDelete
  4. Hi Anonymous,

    is the Email address you are sending Email to is in the same domain as your site?
    so e.g. if your site is testing.sharepoint.com
    so your email to address must be like, example@testing.onmicrosoft.com.
    Otherwise it wont send the email. "Email To" should be on the same domain to successfully send email.

    ReplyDelete
  5. Thanks for your quick reply.

    Actually our company using google's service for email .I mean to say is our email ids are like anonymous@i2econsulting.com where i2econsulting.com is domain name provided by google.
    In this case can I send emails.

    ReplyDelete
  6. In My Experience you cannot use that, Because you can ONLY send emails to Microsoft Accounts and that too only to the same domain of the SharePoint Hosted APP.

    ReplyDelete
  7. In my case I want to send emails whenever any item added in list using my sharepoint hosted app.
    Do you have any idea how to achieve this.mainly email sending part.

    ReplyDelete
  8. Hasan,

    Great post. I was able to implement very well in my SharePoint Online instance. Were you ever able to figure out how to send to multiple recipients?

    Thanks!

    ReplyDelete
  9. Yes, I was. Sadly I didn't had enough time to write a blog about that. Will do that tomorrow.

    ReplyDelete
    Replies
    1. Would you be able to send a short description of how you sent to multiple recipients? I'm stuck on this one point.

      Thanks!

      Delete
    2. Ok, I think its about time i finish and publish that blog. i'll do that in a while.

      Delete
  10. is it possible to create a three level approval process workflow with SharePoint hosted app?.
    My requirement is to create training request with three level approval and also send emails to the current login user manager...?
    I am stuck in that point.
    Is there any way to proceed>? Please help me, it would be very helpful..

    ReplyDelete
    Replies
    1. I'm not sure about three level approval haven't tried it. but you can send email for sure :)

      Delete
    2. Im getting the Error. - Unable to get property 'WorkflowServicesManager' of undefined or null reference.

      Delete
    3. I am able to send email to the users. We need to add the script.
      src="/_layouts/15/sp.workflowservices.js"
      Is it possible for List Workflow?????

      Delete
    4. I got this error also. any advice would be helpful
      Thanks..

      Delete
    5. I got this error also any advice would be appreciate. thanks.

      Delete
  11. Hello,
    I have tried this example but it works just when it is called from default.aspx page.
    If I want to send emails from another page it does nothing.

    Any help would be appreciated.

    Claudia

    ReplyDelete
  12. Its me again...I found the problem and it was that I was trying to call the send function one per each user and that did not work. So it is going to be needed to add all recipients once.

    Thanks for your post, it was very helpful.

    Claudia

    ReplyDelete
    Replies
    1. You are more than welcome, I'm glad I could help

      Delete
  13. Hi Hasan Nasir,
    I was follow the example you posted, but I getting error SP.WorkflowServices Unable to get property or undefined. Pls help me resolve this.
    Thanks,
    Avata

    ReplyDelete