HOWTO: Send mail on behalf of another user

Question

Many mail agents including Outlook support sending email from one user on behalf of another one. When you reply to such message, the response is sent to the user on whose behalf the message it was sent. One of the usage scenarios is a support group where emails are sent by each member on behalf of the whole group. A reply to any such e-mail is therefore sent to the group.

Microsoft Outlook displays the sender of such email as "alice@example.com of behalf on bob@example.com".

Can this be achieved with Rebex Mail for .NET?

Answer

Yes, this is easily possible using the MailMessage class – just you use the code from this tutorial and add the following line:

message.Sender = "alice@example.com"

The resulting e-mail from field will appear as "alice@example.com of behalf on bob@example.com"

Also worth noting is that the From property (and field) can contain multiple e-mail originators, while the Sender property (and field) can only contain either one address or none. Also, when the From is set to multiple originators, the Sender should be set as well. For detailed information about From, Sender and also Reply-To field, consult section 3.6.2 of RFC 2822.

Complete source code follows:

C#:
using Rebex.Mail;
using Rebex.Net;
using Rebex.Mime.Headers;
...

// create an instance of MailMessage 
MailMessage message = new MailMessage();

// and set its properties to desired values
message.From = "bobr@example.com";
message.Sender = "alice@example.com";
message.To = "joe@example.com";
message.Subject = "This is a simple message";
message.BodyText = "Hello, Joe!";

// send the message
Smtp.Send(message, "smtpserver.example.com");
VB.NET:
'Imports Rebex.Mail 
Imports Rebex.Net 
Imports Rebex.Mime.Headers 
...

' create an instance of MailMessage  Dim message As New MailMessage

' and set its properties to desired values 
message.From = new MailAddressCollection("bob@example.com") 
message.Sender = new MailAddress("alice@example.com") 
message.To = new MailAddressCollection("joe@example.com") 
message.Subject = "This is a simple message" 
message.BodyText = "Hello, Joe!"

' send the message 
Smtp.Send(message, "smtpserver.example.com")

This sample applies to the following components: Rebex Mail for .NET, Rebex Secure Mail for .NET, Rebex Total Pack