开发者

How to add custom headers to the System.Net.Mail SMTP class?

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:the.only.allowed.sender@mydomain.com
>rcpt to:magnus@mydomain.com
>data
From:magnus@mydomain.com
To:some.user@mydomain.com
Subject:Test
Test message
.

When this email has arrived at the recipient, the from address is magnus@mydomain.com, 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("the.only.allowed.sender@mydomain.com");
var toAddres开发者_开发技巧s = new MailAddress("user@mydomain.com");
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("magnus@mydomain.com"),

})
{
  message.Headers.Add("From", "magnus@mydomain.com"); // <---- 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?


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):

var message = new MailMessage(fromAddress, toAddress)
{
  Subject = subject,
  Body = body,
  From = new MailAddress("magnus@mydomain.com"),
  Sender = new MailAddress("the.only.allowed.sender@mydomain.com")
};

smtp.Send(message);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜