2016-11-04 33 views
0

我在system.net> mailSetttings> smtp标签的from部分的应用程序配置文件中指定了“from”地址。如何使用应用程序配置文件中指定的“from”地址在.net中发送smtp消息?

不过,我显然必须指定在构造MAILMESSAGE代码中的“发件人”地址了。当我在代码中执行代码时,代码中的地址将覆盖配置文件中的地址。 我应该怎么做才能使用配置文件中的“来自”地址?使用null或空字符串会导致异常。

代码:

MailMessage notificationMessage = new MailMessage(/*cannot be null or empty here!*/null, toAddress) 
{ 
    Subject = subject, 
    Body = messageBodyText, 
    IsBodyHtml = false, 
    SubjectEncoding = Encoding.UTF8, 
    BodyEncoding = Encoding.UTF8 
}; 

回答

1

您可以编写代理类的邮件,并在这个类可以从价值:)简单而丑陋的解决方案,但很容易:)

+0

我在寻找的东西更优雅而慵懒,否则我可以只使用一个自定义集合的配置文件中毕竟 - 如果你不能使用它,这个“from”属性是什么? :) – Greg

+0

“发件人”是例如的默认值。 “[email protected]”,这个参数可以是构造函数中的最后一个,也可以是可选的:)但是这个解决方案非常难看,必须是标签todo :) –

0

硬编码默认明白了:

//use the constructor without parameters   
MailMessage notificationMessage = new MailMessage() 
{ 
    Subject = subject, 
    Body = messageBodyText, 
    IsBodyHtml = false, 
    SubjectEncoding = Encoding.UTF8, 
    BodyEncoding = Encoding.UTF8, 
}; 
//add the To address later 
notificationMessage.To.Add(toAddress); 
//from not specified, the default value from the app/web.config will be used. 
相关问题