MailKit系列之转发电子邮件

原文:http://www.it1352.com/429181.html

问题

我尝试通过MailKit访问一个IMAP账号,我设法下载邮件(作为的MimeMessage),并在某些时候我需要转发给其他帐户。
展示原始邮件的所有信息(不会忽略,标题,正文内容等)的最佳方式是什么?

解决方案

说“转发”时,不同的人意味着不同的想法,所以我想我会提供答案的不同含义的我能想到的。

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"));

// 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);
}

 

posted @ 2019-04-12 11:53  心存善念  阅读(570)  评论(0编辑  收藏  举报