14

When creating a MailMessage object by calling the "CreateMailMessage" method on the MailDefinition class, the third parameter is an object of type System.Web.UI.Control.

MailDefinition mail = new MailDefinition();

ListDictionary replacements = new ListDictionary();
replacements.Add("<%myname%>", "John");

mail.BodyFileName = "~/App_Data/Emails/SomeEmail.txt";
mail.From = "me@example.com";
mail.Subject = "Hello";

MailMessage message = mail.CreateMailMessage("example@example.com,", replacements, );

Why is that?
And in the case that I don't have an object of that type, what should I pass instead? Just a new Control object?

Control control = new Control();

UPDATE

I would highly recommend using Razor to build email templates. It has great syntax, works great, and doesn't have any weird dependencies!

John B
  • 20,062
  • 35
  • 120
  • 170

5 Answers5

5

Usually you just pass this as the control.

MailMessage message = mail.CreateMailMessage("example@example.com,", replacements, this);

As for the reason why, here is what MSDN says:

The owner parameter indicates which control is the parent of the MailDefinition control. It determines which directory to search for the text file specified in the BodyFileName property.

Andrew Hare
  • 344,730
  • 71
  • 640
  • 635
3

The CreateMailMessage function internally uses the specified Control to query its AppRelativeTemplateSourceDirectory property and its OpenFile method to read the contents of the body (specified in the BodyFileName property of the MailDefinition).

Seems poor design and unnecessary tight coupling for me.

György Balássy
  • 2,938
  • 1
  • 28
  • 23
  • 2
    Indeed! But with the advent of the Razor templating engine, it doesn't really matter anymore :P http://razorengine.codeplex.com/ in case you've been living under a rock :) – John B Jan 26 '12 at 18:26
  • @JohnBubriski Can I use ***RazorEngine*** in _ASP.NET_ **WebForms** application ? – Kiquenet Oct 07 '15 at 07:47
2

You can also just do this:

MailMessage message = this.Mail.CreateMailMessage("no-reply@example.com", dictionary, new System.Web.UI.Control());
Gašper Sladič
  • 867
  • 2
  • 15
  • 32
1

I have been using new LiteralControl() for the 3rd parameter because my messages are being sent from a Workflow. It works. But I do not have an answer for "Why".

Scott Rippey
  • 15,614
  • 5
  • 70
  • 85
0

It sounds like you may not need to use the MailDefinition class at all if you're not binding to any controls. To simply send an email over smtp, you should use a System.Net.Mail.SmtpClient with a System.Net.Mail.MailMessage.

Todd
  • 620
  • 4
  • 13