Can't override "From" address in MailMessage class using .config login credentials

Posted by Jeff on Stack Overflow See other posts from Stack Overflow or by Jeff
Published on 2010-05-25T13:23:56Z Indexed on 2010/05/25 14:01 UTC
Read the original article Hit count: 326

Filed under:
|

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, "[email protected]" does NOT display when the email is received. It still shows as "[email protected]" 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("[email protected]", "Sparky");
   myMailMessage.To.Add(new MailAddress("[email protected]", "receiver name"));

   SmtpClient mySmtpClient = new SmtpClient();

    mySmtpClient.Send(myMailMessage);

in App.config:

<system.net>
  <mailSettings>
    <smtp deliveryMethod="Network" from="[email protected]">
      <network host="smtp.gmail.com" port="587" userName="[email protected]" password="mypassword" defaultCredentials="false"/>
    </smtp>
  </mailSettings>
</system.net>

© Stack Overflow or respective owner

Related posts about c#

Related posts about email