我按照这种模式发送邮件:
public static bool SendPasswordMail(MembershipUser user, Control owner, string password)
{
var definition = new MailDefinition { BodyFileName = string.Concat(AccountRoot, "password.htm"), IsBodyHtml = true };
var subject = "Your new password - {0}".FormatWith(ApplicationConfiguration.ApplicationName);
var data = ExtendedData(DefaultData, subject, user);
data.Add("<%Password%>", password);
return definition.CreateMailMessage(user.Email, data, owner).Send(subject);
}
public static bool Send(this MailMessage message, string subject)
{
try
{
using (message)
{
message.Subject = subject;
using (var client = new SmtpClient())
client.Send(message);
}
}
catch
{
return false;
}
return true;
}
与其将主题设置为“您的新密码 - 网站”,不如将发件人用户名设置为“网站”,并将主题设置为“您的新密码”。但我不知道如何设置发件人用户名。
我在 web.config 中的 smtp 元素如下所示:
<smtp deliveryMethod="Network" from="noreply@site.com">
<network host="localhost" port="25" userName="noreply@site.com" password="******" />
</smtp>
请您参考如下方法:
看看 MailDefinition.CreateMailMessage Method MSDN 上的定义。
它指定第二个参数(IDictionary 对象,示例代码中的变量“data”)应包含在电子邮件消息中替换的字符串。
使用此对象,您可以像这样添加发件人地址的替换:
data.Add("<%From%>", "fromaddress@domain.com");
然而,由于使用 SMTP 伪造发件人地址的能力,几乎所有邮件交换器都将使用电子邮件验证系统,例如 Sender Policy Framework (SPF)以确保收到的电子邮件是从有效来源发送的。
因此,如果您希望收件人收到您的电子邮件,则不能在发件人字段中使用任何电子邮件地址。您必须使用与您从中发送的域相匹配的电子邮件地址。还需要更改 DNS 才能进行必要的检查。
检查此链接:An Overview of the Sender Policy Framework
它指出:
SPF is easy to understand. The "Internet" uses DNS (Domain Name System) to resolve Domain Names (as an example www.msexchange.org) into IP addresses. DNS is also used to direct requests for different services like e-mail and Web Servers. For every Domain around the world an MX (Mail Exchanger) record must exist. An MX record tells the e-mail sender where the target server for receiving mail is located.
SPF is publishing "reverse MX" records in DNS which tells the mail sender which machines send mail from the domain.
The recipient of the e-mail can now check these records to ensure that e-mail is coming from a „trusted“ sender from this domain.
These "reverse MX" records can be easily published in DNS. It takes only one line in DNS to fullfil all requirements. I will give you an example later in this article.
SPF operates at the level of the SMTP transaction, and requires at most three pieces of information:
The MAIL FROM: parameter of the incoming mail The HELO or EHLO parameter of the sending SMTP server (used for Mailer-Deamon bounces which send a blank MAIL FROM) The IP address of the sending SMTP server
编辑
无法在创建时将发件人别名(显示名称)传递给 MailDefinition,我不确定如何将数据添加到 IDictionary 对象,但以下应该有效(在发送扩展方法中):
message.Subject = subject;
message.From = new MailAddress(message.From.Address, "Display Name");
希望这对您有所帮助。
