Is there an elegant automatic way how not to send MailMessage emails without commenting them out? I don't wan't to modify my code every time I am testing something in pages thats uses MailMessages.
Asked
Active
Viewed 341 times
0
-
1Are you aware of compiler directives, as shown in [C# Compiler Directives](https://stackoverflow.com/questions/2920239/c-sharp-compiler-directives)? – Andrew Morton Aug 11 '20 at 10:58
-
You can use #IF DEBUG to make an instance of the SendMailMessage function that won't actually send the mails – Krystian Borysewicz Aug 11 '20 at 10:59
-
[How to execute code only in debug mode in ASP.NET](https://stackoverflow.com/q/1734741/8967612), [Determine if ASP.NET application is running locally](https://stackoverflow.com/q/691881/8967612) – 41686d6564 stands w. Palestine Aug 11 '20 at 10:59
-
As mentioned, compiler directives would be fine. You could also use environmental configuration file entries to set the "verbosity" of your emails. – gmiley Aug 11 '20 at 11:02
-
A far more elegant way than disabling email messages is to simply change your server configuration to point to an alternative SMTP server, such as [MailHog](https://github.com/mailhog/MailHog) or [Papercut](https://github.com/ChangemakerStudios/Papercut-SMTP). Then you make sure you're testing the exact same code you'd otherwise be testing, you can verify that emails get generated properly, and there's no chance of them being accidentally delivered to an actual user. – mason Aug 11 '20 at 13:28
-
Thank you all for those great helpful answers! – raven_977 Aug 11 '20 at 13:53
1 Answers
6
a method i have used in the past is to have the configuration for your SMTP server in your web.config
or app.settings.json
and when you are performing local development point it towards a local instance of https://github.com/mailhog/MailHog or equivalent. This will catch all the emails you send without every having to worry about actually letting them out into the world
Your code would remain unchanged which is the best part.

Andrew Calderwood
- 76
- 1
- 1