nouptime
nouptime

Reputation: 10449

Sending e-mails to users in specific roles

I'm using a custom membership provider based on SimpleMembership together with ASP.NET's DefaultRoleProvider. I want to send an e-mail to the site administrators every time a new item is added to the database.

This is the model for users:

public class Users
{
    public int UserId { get; set; }
    public string UserName { get; set; }
    public string FullName { get; set; }
    public string Email { get; set; }

    public IEnumerable<Role> Roles { get; set; }
}

I've tried the following code to list the UserName of each user in the Administrator role into a ViewData and it works fine:

string userRoles = string.Concat(Roles.GetUsersInRole("Administrator"));
ViewData.Add("UserRoles", userRoles);

How can I output the Email field instead of the UserName into a ViewBag and return them into a class called UserMailer?

Upvotes: 1

Views: 108

Answers (1)

trailmax
trailmax

Reputation: 35116

For every username you'll have to retrieve a user object from membership and use email from user object.

MembershipProvider has method GetUser(string username, bool UpdateLastSeenTimestamp). This gives you back an object MembershipUser that has Email property.

So for every username that you get back from role provider you'll need to call that method:

// pseudocode, not tested
var usernames = Roles.GetUsersInRole("Administrator");
var users = new List<MembershipUser>();
var emails = new List<String>();
foreach(var username in usernames){
    var user = MembershipProvider.GetUser(username, false);
    users.Add(user);
    emails.Add(user.Email);
}

so users contain list of user objects - if you need them somewhere. And emails will contain list of emails for these users.

p.s. Don' use ViewData to pass emails to your components (Mailer). ViewData is only meant to pass information to/from view, not between your classes.

Upvotes: 1

Related Questions