Sending emails in C# is a simple task. All you need is a MailMessage object with your email and a SmtpClient to send it:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
var message = "your message goes here"; // create the email var mailMessage = new MailMessage(); mailMessage.To.Add(toAddress); mailMessage.Subject = "Sending emails is easy"; mailMessage.From = new MailAddress(fromAddress); mailMessage.Body = message; // send it (settings in web.config / app.config) var smtp = new SmtpClient(); smtp.Send(mailMessage); |
The configuration for the SmtpClient is inside the web.config or app.config can look like this example from Sanjay kumar:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<configuration> <system.net> <mailSettings> <network host="smtp.gmail.com" port="587" password="yourpassword" enableSsl="true"/> </smtp> </mailSettings> </system.net> </configuration> |
Whenever your code is executed, your email will be sent using the specified mail server. While this is great for production, it’s a different story for testing your code. Do you really want to send all those emails?
A Different Delivery Method
The great benefit of using a configuration based approach with the mail configuration settings is that you can change the configuration in the app.config and don’t need to modify your code. If you switch the configuration from above with this one, then the SmtpClient will store the emails instead of sending them:
1 2 3 4 5 6 7 8 9 |
<configuration> <system.net> <mailSettings> <smtp deliveryMethod="SpecifiedPickupDirectory" > <specifiedPickupDirectory pickupDirectoryLocation="c:\temp\maildrop"/> </smtp> </mailSettings> </system.net> </configuration> |
Attention: make sure that the pickup directory exists. Otherwise you will get an exception.
SmtpClient obsolete in
System.Net.Mail.SmtpClient is marked as obsolete in docs, but not in the source code
https://github.com/dotnet/docs/issues/1876
MailKit Officially Replaces .NET’s SmtpClient
https://www.infoq.com/news/2017/04/MailKit-MimeKit-Official
Hi,
Thanks for pointing that out. Without a remark in the code one will not find such an important info. It’s a bit disappointing that the issue in GitHub is still open and no clear answer was posted.
Thanks again,
Johnny