.net-如何为MailMessage ReplyTo属性分配值?

我想为.NET MailMessage设置ReplyTo值。

MailMessage.ReplyTo属性:

该类型的ReplyTo已过时。   请改用ReplyToList   可以接受多个地址。

MailMessage.ReplyToList属性:

获取或设置地址列表为   回复邮件。

但是,ReplyToList是ReadOnly。

我试图像这样使用MailMessage.Headers属性:

mail.Headers.Add("Reply-To", "johndoe@example.com");

如此处所述:System.Web.Mail,我的天哪!

但是,这似乎不起作用。

如何设置MailMessage的ReadOnly属性ReplyToList的值?

Zack Peterson asked 2020-02-13T20:29:57Z
7个解决方案
109 votes

ReplyToList是MailAddressCollection的实例,它公开了Add方法。

要添加新地址,您只需将地址作为字符串传递

  message.ReplyToList.Add("john.doe@example.com");
Giorgi answered 2020-02-13T20:30:15Z
9 votes

我喜欢数组初始化语法,它将为您调用Add()。

var msg = new MailMessage("noreply@example.com", mailTo) {
    Subject = "my important message",
    Body = this.MessageBody,
    ReplyToList = { mailTo } // array init syntax calls Add()
};
mailClient.Send(msg);
yzorg answered 2020-02-13T20:30:35Z
6 votes

你不能说

message.ReplyToList = new MailAddressCollection();

创建一个新集合。 但是,您想要做的就是添加到现有集合中。

message.ReplyToList.Add(new MailAddress("foo@bar.net"));
Anthony Pegram answered 2020-02-13T20:30:59Z
6 votes

我的答案与已经给出的公认答案没有什么不同。 但是,我认为需要提供它。

var fromEmail = new MailAddress("foobar@example.com", "Foo Bar");
var replyEmail = new MailAddress("foo@example.com", "Foo Example");
var msgEmail = new MailMessage { From = fromEmail };
msgEmail.ReplyToList.Add( replyEmail );
Taersious answered 2020-02-13T20:31:19Z
2 votes

我改用MailMessage.Sender属性。

mail.Sender = new Mail.MailAddress("system@example.com");
mail.From = new Mail.MailAddress("johndoe@example.com", "John Doe");

更多信息:MailMessage,发件人和发件人属性之间的区别

Zack Peterson answered 2020-02-13T20:31:43Z
0 votes

您需要通过Add方法将ReplyTo地址列表添加到ReplyToList:

            mail.Sender = new MailAddress(from, displayName);
            mail.From = new MailAddress(from, displayName);
            mail.ReplyToList.Add("replyToAddress@host.com");
Adel P.G. answered 2020-02-13T20:32:03Z
0 votes
MailMessage.ReplyToList.Add("johndoe@example.com, janedoe@example.com, xxxx@yyyy.com");

参考 [https://docs.microsoft.com/zh-cn/dotnet/api/system.net.mail.mailaddresscollection.add?redirectedfrom=MSDN&view=netframework-4.8#overloads]


我希望也可以使用上述方法(可能使用此格式)来包括“友好名称”:Jon Doe <jondoe@example.com>

参考:[https://askleo.com/why_are_email_addresses_sometimes_in_anglebrackets/,][https://help.returnpath.com/hc/en-us/articles/220563147-What-is-a-Friendly-From-name-and-address-,][https://wordtothewise.com/2014/12/friendly-email-addresses/。]

Zeek2 answered 2020-02-13T20:32:33Z
translate from https://stackoverflow.com:/questions/2758699/how-do-i-assign-a-value-to-a-mailmessage-replyto-property