Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forward email using MailKit (C#)

I'm trying to access to an IMAP account using MailKit (created by jstedfast)

I manage to download the message (as a MimeMessage), and at some point I need to "forward" it to another account.

How would be the best way to do it, in order to preserve all the information of the original email (adresses, headers, body content, etc).

Thanks!

like image 904
Xavi Ivars Avatar asked Apr 02 '15 14:04

Xavi Ivars


People also ask

What is MailKit?

MailKit is an Open Source, . NET mail client library for Windows, MAC, Linux and Mobile Platforms such as iOS and Android built on top of MimeKit. We get all the mail sending libraries from MailKit, such as - Simple Mail Transfer Protocol (SMTP) etc.

How do I send an email in MailKit?

The documentation for MailKit has a good example on how to send emails. You create a MimeMessage (instead of a MailMessage) and then send it with the SmtpClient class: message.Subject = "How you doin'?"; I just wanted to let you know that Monica and I were going to go play some paintball, you in?

What is MimeKit MailKit?

What is MailKit? MailKit is a cross-platform mail client library. That means you can not only send emails, but you also get everything you need to receive emails. Thanks to MimeKit on that MailKit is built on, you can do everything imaginable with the email itself. The more complex your tasks with emails are, the better suited is MailKit.

How to add MailKit in ASP NET Core?

Adding MailKit in ASP.NET is not so tricky. You can prefer to use both project.json or Nuget Package Manager. I prefer to use Nuget Package manager to install and manage dependencies in my Project. Right click on your ASP.NET Core Project and select Manage Nuget Packages. Select Search for MailKit under Browse and Install as shown in figure.

How do I forward an email message?

Forward the message by attaching it (in whole) to a new message, the way some email clients might do it. 4. Forward the message "inline" the way many other email clients do it.


1 Answers

Different people mean different things when they say "forward", so I guess I'll provide answers to the different meanings that I can think of.

1. Forward (Resend) the message without any changes.

By "no changes", I literally mean no changes at all to the raw message data. The way to do this is to do:

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", "[email protected]");
    var recipients = new [] { new MailboxAddress ("John Smith", "[email protected]") };

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

Note: Some webmail providers such as GMail, Hotmail/Office365, etc. might not allow you to use this approach as they might consider it to be email spoofing. These mail hosts might replace the From header with the name/email address of your account, so be aware of this potential issue.

Usually people don't mean this type of "forwarding", though. If they want to resend, usually they'll use the next method of resending.

2. Forward (Resend) the message the way that an automated filter might send it.

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", "[email protected]"));
message.ResentReplyTo.Add (new MailboxAddress ("MyName", "[email protected]"));
message.ResentTo.Add (new MailboxAddress ("John Smith", "[email protected]"));
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. Forward the message by attaching it (in whole) to a new message, the way some email clients might do it.

var messageToForward = FetchMessageFromImapServer ();

// construct a new message
var message = new MimeMessage ();
message.From.Add (new MailboxAddress ("MyName", "[email protected]"));
message.ReplyTo.Add (new MailboxAddress ("MyName", "[email protected]"));
message.To.Add (new MailboxAddress ("John Smith", "[email protected]"));
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);
}

4. Forward the message "inline" the way many other email clients do it.

var messageToForward = FetchMessageFromImapServer ();

// construct a new message
var message = new MimeMessage ();
message.From.Add (new MailboxAddress ("MyName", "[email protected]"));
message.ReplyTo.Add (new MailboxAddress ("MyName", "[email protected]"));
message.To.Add (new MailboxAddress ("John Smith", "[email protected]"));
message.Subject = "FWD: " + messageToForward.Subject;

// now to create our body...
var builder = new BodyBuilder ();

using (var writer = new StringWriter ()) {
    var sender = messageToForward.From.Mailboxes.FirstOrDefault () ?? messageToForward.Sender;
    var senderName = sender != null ? (!string.IsNullOrEmpty (sender.Name) ? sender.Name : sender.Address) : "someone";
    var text = messageToForward.TextBody ?? string.Empty;

    writer.WriteLine ("On {0}, {1} wrote:", messageToForward.Date, senderName);

    using (var reader = new StringReader (text)) {
        string line;

        while ((line = reader.ReadLine ()) != null) {
            writer.Write ("> ");
            writer.WriteLine (line);
        }
    }

    builder.TextBody = writer.ToString ();
}

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);
}
like image 193
jstedfast Avatar answered Oct 09 '22 02:10

jstedfast