lunedì 25 novembre 2013

C# - How to set the Mail From Envelope

When you send an email using System.Net.Mail you can set the field FROM but you can not set the SMTP MAIL FROM envelope. It is possible to set that value just using the MailMessage.Sender property. Here it is the code:

using (MailMessage mailMsg = new MailMessage())
{
    mailMsg.Subject = "Hello There";
    mailMsg.Body = "This is a test.";
    mailMsg.To.Add(new MailAddress("xxxxx@gmail.com"));
    mailMsg.ReplyToList.Add("replyhere@gmail.com");
    mailMsg.From = new MailAddress("me@gmail.com", "Alessandro");
    mailMsg.Sender = new MailAddress("somereturnpath@example.co.uk");
    SmtpClient client = new SmtpClient
    {
        Host = "localhost",
        DeliveryMethod = SmtpDeliveryMethod.Network
    };
 
    client.Send(mailMsg);
}

It is important to set the DeliveryMethode to "Network" in order to let the system to set the MAIL FROM envelope from the sender.

And here is the proof: