MailDefinition / MailMessage和basepath不能为null

时间:2014-02-20 10:09:54

标签: asp.net-mvc mailmessage

我正在使用下面的代码创建MailMessage,并在调用mail.CreateMailMessage时收到此错误。

  

值不能为空。参数名称:basepath

任何人都知道可能出现什么问题?

public void SendReciept(string reciever)
    {
        MailDefinition mail = new MailDefinition();
        mail.IsBodyHtml = true;

        mail.BodyFileName = "~/file.txt";
        mail.Subject = "Subject";
        mail.From = "noreply@xxx.com";
        mail.Priority = System.Net.Mail.MailPriority.Normal;

        MailMessage message = mail.CreateMailMessage(reciever, RecieptReplacements, new System.Web.UI.Control());

        ...
    }

    ListDictionary RecieptReplacements
    {
        get
        {
            ListDictionary replacements = new ListDictionary();

            replacements.Add("<%Name%>", "Name");

            return replacements;
        }
    }

1 个答案:

答案 0 :(得分:1)

您需要创建一个Web用户控件(.ascx文件),然后加载该控件并将其传递给CreateMailMessage

// Create a dummy page and use it to load a dummy control so that CreateMailMessage() will not complain
Page page = new Page();
DummyControl control = (DummyControl)page.LoadControl("~/DummyControl.ascx");           
MailMessage message = mail.CreateMailMessage(reciever, RecieptReplacements, dummycontrol);

看看这个answer,它解释了原因并提供了上述解决方案。