Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there way to see if System.Net.Mail worked

Tags:

c#

email

asp.net

I'm using System.Net.Mail to send email, like so :

MailMessage message = new MailMessage();

message.From = new MailAddress("[email protected]");
message.To.Add(new MailAddress("[email protected]"));


message.Subject = "Hello";
message.Body = "This is a nice body..";

SmtpClient client = new SmtpClient();
client.Send(message);

How can i know if the E-mail was sent, can i put in a if sentence to check it out ? What would it look like then ?

like image 997
eski Avatar asked Feb 28 '23 02:02

eski


1 Answers

You might want to wrap your SMTP call into a try...catch block - that way you can easily catch any obvious SMTP related errors that might happen:

try
{
   SmtpClient client = new SmtpClient();
   client.Send(message);
}
catch(Exception exc)
{
   // log the error, update your entry - whatever you need to do 
}

This will handle the most obvious errors, like

  • SMTP server not found
  • SMTP server not responding
  • SMTP refusing you to send (e.g. because you didn't provide any or valid credentials)

Once the SMTP server has your message, it's out of your .NET hands.... you can't really do much (except check for the SMTP server's logs for errors).

If you want to check and see whether your SMTP mails actually are "sent out", you can also add these lines of code to your app's app.config (or web.config) and let .NET put your mails into a directory (as EML files):

  <system.net>
    <mailSettings>
      <smtp deliveryMethod="SpecifiedPickupDirectory">
        <specifiedPickupDirectory pickupDirectoryLocation="C:\temp\mails"/>
      </smtp>
    </mailSettings>
  </system.net>

Your mails will now be stored into the C:\temp\mails directory as EML files and you can have a look at them and check to see whether they are as they should be.

like image 191
marc_s Avatar answered Mar 07 '23 15:03

marc_s