我正在为我的项目使用Mailkit库(Imap)。
我可以通过SmtpClient轻松发送新消息。
目前我正在挖掘如何回复特定邮件。是否可以为该回复邮件添加更多收件人?
@jstedfast感谢精彩的一个:)
答案 0 :(得分:11)
回复邮件非常简单。在大多数情况下,您只需创建回复邮件的方式与创建任何其他邮件的方式相同。只有一些细微差别:
Subject
标题加"Re: "
前缀(换句话说) ,如果您使用Subject
"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不为null。尽管不太可能,但这可能发生(意味着该消息不包含text/plain
正文)。