change sender address when sending mail through gmail in c#

ACP picture ACP · Oct 6, 2010 · Viewed 44.6k times · Source

I have used the following code to send mail from my web application using a gmail account. My question is, can i change the sender address to another address other than original sender(gmail) address? My code is as follows:

System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();
System.Net.NetworkCredential cred = new System.Net.NetworkCredential("[email protected]", "*******");

Whatever i do is useless as i always receive mail from [email protected]. Is it possible to change it?

I have changed to mail.From = new System.Net.Mail.MailAddress("[email protected]"); but i received the mail with the from address [email protected] and not from the new "From" address. I think gmail smtp overwrites the from address with the original credential.

Answer

philip picture philip · Jan 4, 2012

This is the solution:

  1. use the codes above to set mail.From = new MailAddress(address, display name)
  2. in Gmail, go to Mail Settings >> Accounts and Import.
  3. Add the email account you will use as sender in "Send Mail As". (tick as Alias)

This works for me