Reputation: 10419
I have an emails
variable that contains a list of e-mail addresses of users in a role. The list is not comma-separated. Here's the code that I have at the moment:
public virtual MvcMailMessage AdminNotification()
{
var userRoles = Roles.GetUsersInRole("Admin");
var users = new List<MembershipUser>();
var emails = new List<String>();
foreach (var UserName in userRoles)
{
var user = Membership.GetUser(UserName, false);
users.Add(user);
emails.Add(user.Email);
}
return Populate(x =>
{
x.Subject = "AdminNotification";
x.ViewName = "AdminNotification";
emails.ForEach(user => x.To.Add(user.Email));
});
}
I get an error stating 'string' does not contain a definition for 'Email'...
What should I use instead of x.To.Add(user.Email)
?
Update #1
I'm able to send out e-mails to the intended recipients, but the message body is blank. The message body has been constructed in a View. It was working before I used the code in the answer below, how can I get it working again?
Upvotes: 2
Views: 1397
Reputation: 545
It is possible to send emails using the original code (using lambda expressions), although there seems to be a usage issue with it. In the code the lines:
return Populate(x =>
{
x.Subject = "AdminNotification";
x.ViewName = "AdminNotification";
emails.ForEach(user => x.To.Add(user.Email));
});
reuse the emails list, which is a list of strings, so instead of referencing a user in the .ForEach, an email string should be the parameter (left hand side), thus the solution would be:
return Populate(x =>
{
x.Subject = "AdminNotification";
x.ViewName = "AdminNotification";
emails.ForEach(email => x.To.Add(email));
});
It might not be of any help, just wanted to clarify that.. :)
Upvotes: 1
Reputation: 10419
Solution for Update #1:
Made some minor tweaks to the code and now it's working as expected, just had to move some things around. Here's the part that was tweaked:
var message = new MvcMailMessage {Subject = "AdminNotification"};
foreach (string email in emails)
{
message.To.Add(email);
PopulateBody(message, ViewName = "AdminNotification");
}
return message;
Upvotes: 1
Reputation: 15148
This is how I'd rewrite it:
public virtual MvcMailMessage AdminNotification()
{
string[] userRoles = Roles.GetUsersInRole("Admin");
IEnumerable<string> emails =
userRoles.Select(userName => Membership.GetUser(userName, false))
.Select(user => user.Email);
var message = new MvcMailMessage {Subject = "AdminNotification", ViewName = "AdminNotification"};
foreach (string email in emails)
{
message.To.Add(email);
}
return message;
}
I hope it helps.
Upvotes: 1