Tuesday, October 18, 2011

How to email members of a SharePoint group

This relates to MOSS 2007.

In doing a state machine workflow, I have noticed how you can assign a SharePoint group to a task no problem, but when you set that group as the recipient of an email activity, you get an error. I wrote a very simple function that takes in the SharePoint group's name as a parameter and returns a semi-colon delimited string of the email addresses of the people in the group. I also had another scenario where I wanted to get the login names of the individuals in the group, too, so I made another parameter that acts as a switch - you choose whether you want login names or email addresses. Just assign the function below to your email task's To property and you are good to go!

Private Function GetGroupInfo(ByVal GroupName As String, ByVal WhatToGet As String) As String
'PURPOSE: returns semicolon-separated string of group member login names or email addresses

Dim strReturnString As String = ""

'get group
Dim TheGroup As SPGroup = workflowProperties.Web.SiteGroups(GroupName)

'loop through group and build string of login names or email addresses
For Each GroupMember As SPUser In TheGroup.Users

If WhatToGet = "LOGIN_NAMES" Then

If strReturnString = "" Then
strReturnString = GroupMember.LoginName
Else
strReturnString = strReturnString & "; " & GroupMember.LoginName
End If

ElseIf WhatToGet = "EMAIL_ADDRESSES" Then

If strReturnString = "" Then
strReturnString = GroupMember.Email
Else
strReturnString = strReturnString & "; " & GroupMember.Email
End If
End If
Next

Return strReturnString

End Function


To get the email addresses of members in a SharePoint group called "Account Personnel" and then assign them to an email activity's To property, type:
MyTaskEmail_To = GetGroupInfo("Account Personnel", "EMAIL_ADDRESSES")

Workflow task link in email

Just wanted to do a quick post on a recent gotcha. I created a MOSS 2007 state machine workflow and added custom email activities to send emails notifying users of their tasks. I wanted to have a link in those emails that pointed directly to the user's task, ie the same link you get when you enable "Send e-mail when ownership assigned?" in the task list's Settings -> List Settings -> Advanced settings screen.

I thought I could simply reference the task's ListItemId property, but it kept coming up as -1. After finding an article on SharePoint Tricks, I realized I needed to create a Field variable for the ListItemId property, then reference the Field variable.

1. In the create task activity, create a Field from the ListItemId (by default it says -1).

2. The link in the email concatenates workflowProperties.SiteUrl, workflowProperties.TaskListUrl, "/DispForm.aspx?ID=", and finally createMyApprovalTask_ListItemId.ToString()


This will link directly to the user's task form on the SharePoint site.

That's it!