tags:

views:

219

answers:

1

I have a SMTP server that only accepts a predefined From sender.
However, I can add a custom from header in the DATA structure to set another from (sender ) address. This is possible if I test using Telnet to compose an email message:

>helo there
>mail from:[email protected]
>rcpt to:[email protected]
>data
From:[email protected]
To:[email protected]
Subject:Test
Test message
.

When this email has arrived at the recipient, the from address is [email protected], which is the goal.
Here's my problem.

How can I mimic this "from header" in the System.Net.Mail SMTP class? Setting the from property fails, because that would violate the SMTP server policies. Something like this would be great, but it doesn't work:

var fromAddress = new MailAddress("[email protected]");
var toAddress = new MailAddress("[email protected]");
string subject = "Subject";
string body = "Body";

var smtp = new SmtpClient
{
  Host = "my-smtp-server",
  Port = 25,
  DeliveryMethod = SmtpDeliveryMethod.Network
};

using (var message = new MailMessage(fromAddress, toAddress)
{
  Subject = subject,
  Body = body,
  ReplyTo = new MailAddress("[email protected]"),

})
{
  message.Headers.Add("From", "[email protected]"); // <---- This would be great, if it worked
  smtp.Send(message);
}

Has anybody got any ideas?

PS. Writing a custom SMTP class myself, using TCP sockets, it works, but can this be done in the standard .NET classes?

+1  A: 

Well, I should have done some experimenting before posting the question...
(But instead of deleting it, I'll leave it here if others would have the same issue).

The solution was to set both the From and Sender properties on the MailMessage object.
(I'd need to set both, otherwise it doesn't work):

using (var message = new MailMessage(fromAddress, toAddress)
{
  Subject = subject,
  Body = body,
  From = new MailAddress("[email protected]"),
  Sender = new MailAddress("[email protected]")
})
{
  smtp.Send(message);
}
Magnus Johansson