我正在尝试使用MailKit访问IMAP帐户(由jstedfast创建)
我设法下载邮件(作为MimeMessage),在某些时候我需要将其“转发”到另一个帐户。
如何最好的方式,以保留原始电子邮件的所有信息(地址,标题,正文内容等)。
谢谢!
答案 0 :(得分:14)
当他们说“前进”时,不同的人意味着不同的东西,所以我想我会提供我能想到的不同含义的答案。
<强> 1。转发(重新发送)邮件而不做任何更改。
通过“无变化”,我的字面意思是对原始消息数据完全没有任何变化。这样做的方法是:
var message = FetchMessageFromImapServer ();
using (var client = new SmtpClient ()) {
client.Connect ("smtp.example.com", 465, true);
client.Authenticate ("username", "password");
var sender = new MailboxAddress ("My Name", "username@example.com");
var recipients = new [] { new MailboxAddress ("John Smith", "john@smith.com") };
// This version of the Send() method uses the supplied sender and
// recipients rather than getting them from the message's headers.
client.Send (message, sender, recipients);
client.Disconnect (true);
}
但通常人们并不是指这种“转发”。如果他们想重新发送,通常他们会使用下一种重发方式。
<强> 2。以标准方式转发(重新发送)消息。
var message = FetchMessageFromImapServer ();
// clear the Resent-* headers in case this message has already been Resent...
message.ResentSender = null;
message.ResentFrom.Clear ();
message.ResentReplyTo.Clear ();
message.ResentTo.Clear ();
message.ResentCc.Clear ();
message.ResentBcc.Clear ();
// now add our own Resent-* headers...
message.ResentFrom.Add (new MailboxAddress ("MyName", "username@example.com"));
message.ResentReplyTo.Add (new MailboxAddress ("MyName", "username@example.com"));
message.ResentTo.Add (new MailboxAddress ("John Smith", "john@smith.com"));
message.ResentMessageId = MimeUtils.GenerateMessageId ();
message.ResentDate = DateTimeOffset.Now;
using (var client = new SmtpClient ()) {
client.Connect ("smtp.example.com", 465, true);
client.Authenticate ("username", "password");
// The Send() method will use the Resent-From/To/Cc/Bcc headers if
// they are present.
client.Send (message);
client.Disconnect (true);
}
第3。通过将消息(整体)附加到新消息(一些邮件客户端可能会这样做的方式)来转发消息。
var messageToForward = FetchMessageFromImapServer ();
// construct a new message
var message = new MimeMessage ();
message.From.Add (new MailboxAddress ("MyName", "username@example.com"));
message.ReplyTo.Add (new MailboxAddress ("MyName", "username@example.com"));
message.To.Add (new MailboxAddress ("John Smith", "john@smith.com"));
message.Subject = "FWD: " + messageToForward.Subject;
// now to create our body...
var builder = new BodyBuilder ();
builder.TextBody = "Hey John,\r\n\r\nHere's that message I was telling you about...\r\n";
builder.Attachments.Add (new MessagePart { Message = messageToForward });
message.Body = builder.ToMessageBody ();
using (var client = new SmtpClient ()) {
client.Connect ("smtp.example.com", 465, true);
client.Authenticate ("username", "password");
client.Send (message);
client.Disconnect (true);
}