You don't need to fake the httpcontext, just break the dependence between your controller and the ActionMailer
. I wrote some wrappers to you.
Mailer.cs:
public interface IMailer
{
void SendMail(string viewName, IEnumerable<string> to, string subject, IEnumerable<string> replayTo);
void SendMail(string viewName, object model, IEnumerable<string> to, string subject,
IEnumerable<string> replayTo);
void SendMail(string viewName, IEnumerable<string> to, string from, string subject, IEnumerable<string> replayTo);
void SendMail(string viewName, object model, IEnumerable<string> to, string from, string subject,
IEnumerable<string> replayTo);
}
public class Mailer : MailerBase, IMailer
{
public void SendMail(string viewName, IEnumerable<string> to, string subject,
IEnumerable<string> replayTo = null)
{
foreach (var email in to)
{
To.Add(email);
}
Subject = subject;
if (replayTo != null)
foreach (var email in replayTo)
{
ReplyTo.Add(email);
}
Email(viewName).Deliver();
}
public void SendMail(string viewName, object model, IEnumerable<string> to, string subject,
IEnumerable<string> replayTo = null)
{
foreach (var email in to)
{
To.Add(email);
}
Subject = subject;
if (replayTo != null)
foreach (var email in replayTo)
{
ReplyTo.Add(email);
}
Email(viewName, model).Deliver();
}
public void SendMail(string viewName, IEnumerable<string> to, string from, string subject,
IEnumerable<string> replayTo)
{
foreach (var email in to)
{
To.Add(email);
}
From = from;
Subject = subject;
if (replayTo != null)
foreach (var email in replayTo)
{
ReplyTo.Add(email);
}
Email(viewName).Deliver();
}
public void SendMail(string viewName, object model, IEnumerable<string> to, string from, string subject,
IEnumerable<string> replayTo)
{
foreach (var email in to)
{
To.Add(email);
}
From = from;
Subject = subject;
if (replayTo != null)
foreach (var email in replayTo)
{
ReplyTo.Add(email);
}
Email(viewName, model).Deliver();
}
}
To use the wrapper, bind him using Ninject or whatever library you want and use it in your controllers.
NinjectWebCommon.cs:
_kernel.Bind<IMailer>().To<Mailer>();
MailController.cs:
private readonly IMailer _mailer;
public MailController(IMailer mailer) {
_mailer = mailer;
}
_mailer.SendMail("Forgot", new ForgotModel
{
UserName = membershipUser.UserName,
Email = user.Email,
Password = membershipUser.ResetPassword()
}, new List<string> { model.Email }, _myEmail, "Your password", new List<string>());