Sunday, August 22, 2010

Sender Property of MailMessage

Many of the time we need to send email on behalf of someone else. For Example, all the employees in the company sending email on behalf of the company. Another common example is invitation email send to the friends by the website on behalf of its user. We have two properties available in MailMessage Class in .NET which are From and Sender which by definition looks very similar but they are different.

When sending a email From Property will contain the Email Address on behalf of whom we are sending the email and Sender property will be the person who is sending the email. Sender is an optional property and is used when we need to send email on behalf of someone else. When we are sending an email  which require authentication (i.e. Credentials) and our MailMessage has Sender property assigned, then Username of NetworkCredential will be same as Sender Email Address.  Below is the code of how we can use it.

Dim msg As New MailMessage
msg.From = New MailAddress("from@domain.com")
msg.Sender = New MailAddress("sender@domain.com")
msg.Subject = "Test Email"
msg.Body = "Hello World. This is a Test Email"

Dim client As New SmtpClient("Host Address", "Port Number")
client.Credentials = New NetworkCredential(msg.Sender.Address, "Password")
client.Send(msg)

Note: Although I have not tested on other SSL Enabled email provider but Sender Property doesn’t work with Gmail. So I think if Smtp Server requires SSL then Sender Property might not work.