Reputation: 21
Not sure if anyone else has run into this issue but I'm trying to send emails using MVCMailer. I was able to get it installed and updated the T4Scaffolding package without any issues.
I have an aspx page that is creating a report and I want that report attached to the email. However, when I turn around and call my SendReport method in the UserMailers class it throws an error on the PopulateBody call saying that routeData is null
Here is my code
public class UserMailer : MailerBase, IUserMailer
{
/// <summary>
/// Email Reports using this method
/// </summary>
/// <param name="toAddress">The address to send to.</param>
/// <param name="viewName">The name of the view.</param>
/// <returns>The mail message</returns>
public MailMessage SendReport(string toAddress, string viewName)
{
var message = new MailMessage { Subject = "Report Mail" };
message.To.Add(toAddress);
ViewBag.Name = "Testing-123";
this.PopulateBody(mailMessage: message, viewName: "SendReport");
return message;
}
}
The error I get is "Value cannot be null. Parameter name: routeData"
I've looked online and haven't found anything that is related to this issue or anyone who has run into this problem.
Upvotes: 2
Views: 755
Reputation: 145880
As Filip said it cannot be used within codebehind in an ASP.NET ASPX page because there is no ControllerContext
/ RequestContext
.
The easiest way for me was to just create a controller action and then use WebClient
to make an http request from the ASPX page.
protected void Button1_Click(object sender, EventArgs e)
{
WebClient wc = new WebClient();
var sendEmailUrl = "https://" + Request.Url.Host +
Page.ResolveUrl("~/email/SendGenericEmail") +
"[email protected]" + "&template=Template1";
wc.DownloadData(sendEmailUrl);
}
Then I have a simple controller
public class EmailController : Controller
{
public ActionResult SendGenericEmail(string emailAddress, string template)
{
// send email
GenericMailer mailer = new GenericMailer();
switch (template)
{
case "Template1":
var email = mailer.GenericEmail(emailAddress, "Email Subject");
email.Send(mailer.SmtpClient);
break;
default:
throw new ApplicationException("Template " + template + " not handled");
}
return new ContentResult()
{
Content = DateTime.Now.ToString()
};
}
}
Of course there are many issues, such as security, protocol (the controller won't have access to the original page), error handling - but if you find yourself stuck this can work.
Upvotes: 0
Reputation: 3742
It is called Mvc Mailer for a reason. You can't use it in a normal asp.net (.aspx) project, only in a MVC project.
Upvotes: 2