Can't override "From" address in MailMessage class using .config login credentials
- by Jeff
I'm updating some existing code that sends a simple email using .Net's SMTP classes. Sample code is below. The SMTP host is google and login info is contained in the App.config as shown below (obviously not real login info :)).
The problem I'm having, and I haven't been able to find any answers Googling, is that I can NOT override the display of the "from" email address that's contained in the "username" attribute off the Network element in the config in the delivered email.
In the line below that explicitly sets the From property off the myMailMessage object, that value, "Sparky@myDomain.com" does NOT display when the email is received. It still shows as "erroruser@myDomain.com" from the Network tag. However, the From name "Sparky" does appear in the email.
I've tried adding a custom "From" header to the Header property of the myMailMessage but that didn't work either.
Is there anyway to login to the smtp server, as shown below using the Network tag credentials, but in the actual email received override the From email address that's displayed?
Sample code:
MailMessage myMailMessage = new MailMessage();
myMailMessage.Subject = "My New Mail";
myMailMessage.Body = "This is my test mail to check";
myMailMessage.From = new MailAddress("Sparky@MyDomain.com", "Sparky");
myMailMessage.To.Add(new MailAddress("receiver@MyDomain.com", "receiver name"));
SmtpClient mySmtpClient = new SmtpClient();
mySmtpClient.Send(myMailMessage);
in App.config:
<system.net>
<mailSettings>
<smtp deliveryMethod="Network" from="errors@mydomain.com">
<network host="smtp.gmail.com" port="587" userName="erroruser@mydomain.com" password="mypassword" defaultCredentials="false"/>
</smtp>
</mailSettings>
</system.net>