Is there a way to see if System.Net.Mail is working

I use System.Net.Mail to send email, for example:

MailMessage message = new MailMessage(); message.From = new MailAddress(" foo@foo.com "); message.To.Add(new MailAddress(" foobar@foobar.com ")); message.Subject = "Hello"; message.Body = "This is a nice body.."; SmtpClient client = new SmtpClient(); client.Send(message); 

How can I find out if an email has been sent, can I add an if clause to check it? What would it look like then?

+4
source share
4 answers

You might want to wrap your SMTP call in a try...catch - this way you can easily catch any obvious SMTP errors that might occur:

 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, for example

  • SMTP server not found
  • SMTP server is not responding
  • SMTP refuses to send you (for example, because you did not provide any valid credentials)

As soon as the SMTP server receives your message, it is out of your hands .NET ... you really can not do much (except checking the SMTP server logs for errors).

If you want to check and verify that your SMTP messages are actually sent, you can also add these lines of code to the app.config (or web.config) application and let .NET put your letters in (as EML files):

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

Now your letters will be saved in the C:\temp\mails as EML files, and you can look at them and check how much they should be.

+6
source

What marc_s says correctly is about using try / catch.

It is worth noting that, although there are no delivery guarantees with SMTP, and trying to develop actual delivery numbers is a very inaccurate science.

There are several methods that some programs try to use, such as image errors and tracking links, but they are not completely reliable.

Many servers will silently trigger a message with an unknown address or, if there are transmission errors, so as not to give too much information to the spam providers.

So, once you have sent it, if there is no exception, you can only hope that it works. One valuable method is to use a regular expression to validate an email address when a user enters it. This helps to avoid some common address problems before they affect mail delivery.

+2
source

You can install and use the DevNullSmtp server - it does not send any e-mail messages, but will register and display all messages and traffic.

0
source

I would consider using third-party services ( smtp.com ) to process messages. They usually provide api tracking that can be requested for successful delivery.

0
source

Source: https://habr.com/ru/post/1308757/


All Articles