In my last post I mentioned that I changed from an internally built Smtp client class based on sockets to using SmtpClient, so that I could avoid problems with running in partial trust. The issue with the old class is that it required SocketPermission with full access in order to send email, which is a pretty broad permission requirement that has some potentially far reaching security implications. So I reworked the class to use SmtpClient with the same class interface to do a drop in replacement.
According to this article on MSDN SmptClient should work in Medium Trust.
Unfortunately my first tests trying to use SmtpClient in Medium Trust ended up failing with:
Description: The application attempted to perform an operation not allowed by the security policy. To grant this application the required permission please contact your system administrator or change the application's trust level in the configuration file.
Haeh? Checking several other sources too seem to point out that this SHOULD indeed work in medium trust.
As it turns out sending through SmtpClient does work in Medium Trust as long as you stick to the default email port (25). What I didn't think about immediately is that my ISP requires me to send email through an alternate port (2525) when I'm not connecting through their network, even when I am using authentication. Using a different port still makes SmtpClient fail with a security permission error.
I suppose this requirement makes some sense but it's neither documented nor obvious. Nor does the error message or call stack offer any indication of the problem.
To get around this issue with a custom port I still have to use a custom policy definition and add:
into the custom permission set defined.
Luckily, I found out today that my ISP has recently dropped the custom port requirement for external email access, so to my surprise I found I actually can send emails on the stock port of 25, which worked without any problems. Apparently the custom port configuration has been a big hassle for the ISAP on the maintenance end as customers call and wonder why their email access doesn't work when they're travelling and so they opened direct port 25 access again. But there are still a number of ISPs that follow this practice so this remains a potential issue and it's something to be aware of in a generic solution.
In the meantime I've updated my code to capture the security exception and provide a more effective error message for the client:
SmtpClient smtp = null;
smtp = new SmtpClient(Server, ServerPort);
catch (SecurityException ex)
this.SetError("Unable to create SmptClient due to missing permissions. If you are using a port other than 25 for your email server, SmtpPermission has to be explicitly added in Medium Trust." );
And life goes on <s>...
Other Posts you might also like