我正在为我的项目使用 Mailkit 库(Imap)。
我可以通过 SmtpClient 轻松地发送一条新消息。
目前我正在研究如何回复特定邮件。是否可以向该回复邮件添加更多收件人?
@jstedfast 谢谢你的精彩:)
回复消息相当简单。在大多数情况下,您只需像创建任何其他消息一样创建回复消息。只有一些细微的区别:
Subject
标头前加上"Re: "
前缀(换句话说,如果您正在回复带有Subject
of的消息"Re: party tomorrow night!"
,则不会为其添加前缀与另一个"Re: "
)。In-Reply-To
头的值。Message-Id
References
标题复制到回复邮件的References
标题中,然后附加原始邮件的Message-Id
标题。如果要在代码中表达这个逻辑,它可能看起来像这样:
public static MimeMessage Reply (MimeMessage message, bool replyToAll)
{
var reply = new MimeMessage ();
// reply to the sender of the message
if (message.ReplyTo.Count > 0) {
reply.To.AddRange (message.ReplyTo);
} else if (message.From.Count > 0) {
reply.To.AddRange (message.From);
} else if (message.Sender != null) {
reply.To.Add (message.Sender);
}
if (replyToAll) {
// include all of the other original recipients - TODO: remove ourselves from these lists
reply.To.AddRange (message.To);
reply.Cc.AddRange (message.Cc);
}
// set the reply subject
if (!message.Subject.StartsWith ("Re:", StringComparison.OrdinalIgnoreCase))
reply.Subject = "Re:" + message.Subject;
else
reply.Subject = message.Subject;
// construct the In-Reply-To and References headers
if (!string.IsNullOrEmpty (message.MessageId)) {
reply.InReplyTo = message.MessageId;
foreach (var id in message.References)
reply.References.Add (id);
reply.References.Add (message.MessageId);
}
// quote the original message text
using (var quoted = new StringWriter ()) {
var sender = message.Sender ?? message.From.Mailboxes.FirstOrDefault ();
quoted.WriteLine ("On {0}, {1} wrote:", message.Date.ToString ("f"), !string.IsNullOrEmpty (sender.Name) ? sender.Name : sender.Address);
using (var reader = new StringReader (message.TextBody)) {
string line;
while ((line = reader.ReadLine ()) != null) {
quoted.Write ("> ");
quoted.WriteLine (line);
}
}
reply.Body = new TextPart ("plain") {
Text = quoted.ToString ()
};
}
return reply;
}
注意:此代码假定 message.TextBody 不为空。虽然不太可能,但有可能发生这种情况(这意味着消息不包含text/plain
正文)。