我正在使用Mailkit库(Imap)完成我的项目。
我可以通过SmtpClient轻松发送新邮件。
目前我正在了解如何回复特定的邮件,以及是否可以将更多的收件人添加到该回复邮件中?
@jstedfast感谢您出色的工作:)
回复消息非常简单。大部分情况下,您只需要像创建任何其他消息一样创建回复消息即可。仅有几个细微的区别:
Subject
头部添加"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不为null。虽然可能性很小,但这种情况确实可能发生(意味着消息不包含text/plain正文)。