Reply to Email in C# and VB.NET

The following example shows how to search for a specific message in the INBOX folder using ImapClient. A reply email message is created in C# and VB.NET with the required reply headers, 'In-Reply-To' and 'References', and a text and HTML body that includes the original message text.

The example ends with the reply message being sent via SmtpClient.

Screenshot

Reply Screenshot

See the full code below.

1using GemBox.Email;
2using GemBox.Email.Imap;
3using GemBox.Email.Mime;
4using GemBox.Email.Pop;
5using GemBox.Email.Smtp;
6using System;
7using System.Collections.Generic;
8using System.Globalization;
9using System.Text;
10
11class Sample
12{
13    [STAThread]
14    static void Main(string[] args)
15    {
16        // If using Professional version, put your serial key below.
17        ComponentInfo.SetLicense("FREE-LIMITED-KEY");
18
19        MailMessage message;
20
21        using (ImapClient imap = new ImapClient("<ADDRESS> (e.g. imap.gmail.com)"))
22        {
23            imap.Connect();
24            Console.WriteLine("Connected.");
25
26            imap.Authenticate("<USERNAME>", "<PASSWORD>");
27            Console.WriteLine("Authenticated.");
28
29            imap.SelectInbox();
30            IList<int> results = imap.SearchMessageNumbers("FROM sender@example.com SUBJECT " +
31                                                           "\"Are you coming to the party\"");
32
33            if (results.Count == 0)
34                Console.WriteLine("Message not found.");
35
36            message = imap.GetMessage(results[0]);
37        }
38
39        MailAddress fromAddress = message.From[0];
40        MailMessage reply = new MailMessage(new MailAddress("receiver@example.com", "Receiver"),
41                                            fromAddress);
42
43        // Add 'In-Reply-To' header
44        Header header = new Header(HeaderId.InReplyTo, message.Id);
45        reply.MimeEntity.Headers.Add(header);
46
47        // Check if 'References' header exists and its body is not null or empty
48        if (message.MimeEntity.Headers.TryGetHeader(HeaderId.References, out header) && !string.IsNullOrEmpty(header.Body))
49            // If found, copy original value and append last message id
50            header = new Header(HeaderId.References, header.Body + ' ' + message.Id);
51        else
52            // If not found, create one with message id
53            header = new Header(HeaderId.References, message.Id);
54
55        // Add 'References' header to reply message
56        reply.MimeEntity.Headers.Add(header);
57
58        // Set subject
59        reply.Subject = "Re: " + message.Subject;
60
61        // Compose text body
62        StringBuilder text = new StringBuilder();
63
64        text.AppendLine("Yes. See you there at 9.");
65        text.AppendLine();
66        text.AppendFormat("On {0}, {1} wrote:", message.Date.ToString(CultureInfo.InvariantCulture), fromAddress);
67        text.AppendLine();
68
69        // Append original text body if it exists
70        if (message.BodyText != null)
71        {
72            text.AppendLine();
73            text.Append("> " + message.BodyText.Replace("\r\n", "\r\n> "));
74        }
75
76        reply.BodyText = text.ToString();
77
78        // Compose HTML body
79        text = new StringBuilder();
80
81        text.Append("<div>Yes. See you there at 9.</div><br/>");
82        text.AppendFormat("<div>On {0}, ", message.Date.ToString(CultureInfo.InvariantCulture));
83
84        if (fromAddress.DisplayName != null)
85            text.Append(fromAddress.DisplayName + ' ');
86
87        text.AppendFormat("<<a href=\"mailto:{0}\">{0}</a>> wrote:<br/>", fromAddress.Address);
88
89        // Append original text body if it exists
90        if (message.BodyHtml != null)
91        {
92            text.Append("<blockquote style=\"margin: 0 0 0 5px;");
93            text.Append(" border-left: 2px blue solid;");
94            text.Append(" padding-left: 5px\">");
95            text.Append(message.BodyHtml);
96            text.Append("</blockquote><br/></div>");
97        }
98
99        reply.BodyHtml = text.ToString();
100
101        Console.WriteLine("Sending reply...");
102
103        // Initialize new SMTP client and send message
104        using (SmtpClient smtp = new SmtpClient("<ADDRESS> (e.g. smtp.gmail.com)"))
105        {
106            smtp.Connect();
107            Console.WriteLine("Connected.");
108
109            smtp.Authenticate("<USERNAME>", "<PASSWORD>");
110            Console.WriteLine("Authenticated.");
111
112            smtp.SendMessage(message);
113        }
114
115        Console.WriteLine("Reply sent successfully.");
116    }
117}
1Imports System.Globalization
2Imports System.Text
3Imports GemBox.Email
4Imports GemBox.Email.Imap
5Imports GemBox.Email.Mime
6Imports GemBox.Email.Pop
7Imports GemBox.Email.Smtp
8
9Module Samples
10
11    Sub Main()
12
13        ' If using Professional version, put your serial key below.
14        ComponentInfo.SetLicense("FREE-LIMITED-KEY")
15
16        Dim message As MailMessage
17
18        Using imap As New ImapClient("<ADDRESS> (e.g. imap.gmail.com)")
19            imap.Connect()
20            Console.WriteLine("Connected.")
21
22            imap.Authenticate("<USERNAME>", "<PASSWORD>")
23            Console.WriteLine("Authenticated.")
24
25            imap.SelectInbox()
26            Dim results As IList(Of Integer) = imap.SearchMessageNumbers("FROM sender@example.com SUBJECT " &
27                                                                         """Are you coming to the party""")
28
29            If results.Count = 0 Then
30                Console.WriteLine("Message Not found.")
31            End If
32
33            message = imap.GetMessage(results(0))
34        End Using
35
36        Dim fromAddress As MailAddress = message.From(0)
37        Dim reply As New MailMessage(New MailAddress("receiver@example.com", "Receiver"),
38                                     fromAddress)
39
40        ' Add 'In-Reply-To' header
41        Dim header As New Header(HeaderId.InReplyTo, message.Id)
42        reply.MimeEntity.Headers.Add(header)
43
44        ' Check if 'References' header exists and its body is not null or empty
45        If message.MimeEntity.Headers.TryGetHeader(HeaderId.References, header) AndAlso Not String.IsNullOrEmpty(header.Body) Then
46            ' If found, copy original value and append last message id
47            header = New Header(HeaderId.References, header.Body & " "c & message.Id)
48        Else
49            ' If not found, create one with message id
50            header = New Header(HeaderId.References, message.Id)
51        End If
52
53        ' Add 'References' header to reply message
54        reply.MimeEntity.Headers.Add(header)
55
56        ' Set subject
57        reply.Subject = "Re:  " + message.Subject
58
59        ' Compose text body
60        Dim text As New StringBuilder()
61
62        text.AppendLine("Yes. See you there at 9.")
63        text.AppendLine()
64        text.AppendFormat("On {0}, {1} wrote:", message.Date.ToString(CultureInfo.InvariantCulture), fromAddress)
65        text.AppendLine()
66
67        ' Append original text body if it exists
68        If message.BodyText IsNot Nothing Then
69            text.AppendLine()
70            text.Append("> " + message.BodyText.Replace(vbCrLf, vbCrLf & "> "))
71        End If
72
73        reply.BodyText = text.ToString()
74
75        ' Compose HTML body
76        text = New StringBuilder()
77
78        text.Append("<div>Yes. See you there at 9.</div><br/>")
79        text.AppendFormat("<div>On {0}, ", message.Date.ToString(CultureInfo.InvariantCulture))
80
81        If fromAddress.DisplayName IsNot Nothing Then
82            text.Append(fromAddress.DisplayName + " "c)
83        End If
84
85        text.AppendFormat("<<a href=""mailto:{0}"">{0}</a>> wrote:<br/>", fromAddress.Address)
86
87        ' Append original text body if it exists
88        If message.BodyHtml IsNot Nothing Then
89            text.Append("<blockquote style=""margin: 0 0 0 5px;")
90            text.Append(" border-left 2px blue solid;")
91            text.Append(" padding-left 5px"">")
92            text.Append(message.BodyHtml)
93            text.Append("</blockquote><br/></div>")
94        End If
95
96        reply.BodyHtml = text.ToString()
97
98        Console.WriteLine("Sending reply...")
99
100        ' Initialize new SMTP client and send message
101        Using smtp As New SmtpClient("<ADDRESS> (e.g. smtp.gmail.com)")
102            smtp.Connect()
103            Console.WriteLine("Connected.")
104
105            smtp.Authenticate("<USERNAME>", "<PASSWORD>")
106            Console.WriteLine("Authenticated.")
107
108            smtp.SendMessage(message)
109        End Using
110
111        Console.WriteLine("Reply sent successfully.")
112
113    End Sub
114
115End Module

Check next sample or find out more about GemBox.Email and GemBox Software.