Reputation: 999
I am trying to build a system for sending newsletters from my website.
I am building it as a console app which I will then execute daily from windows scheduler.
I want to have some logging in the system, so I am adding the most simple log "feature".
The mails are sent fine, but I would like to write in the log when a mail is sent. The problem is that I don't know how to get an event from the SmtpClient when the mail was sent or the mail was not sent.
public void SendMails(List<Agent> agents, string logfilename)
{
foreach (Agent agent in agents)
{
MailMessage mail = new MailMessage();
mail.....
SmtpClient client = new SmtpClient();
client.....
try
{
client.Send(mail);
WriteLog(logfilename, "Sent mail to: " + mail.To[0].Address);
}
catch (SmtpException smtpexception)
{
WriteLog(logfilename, "SMTP EXCEPTION: " + smtpexception.Message);
}
catch (Exception e)
{
WriteLog(logfilename, "EXCEPTION: " + e.Message);
}
}
}
public void WriteLog(string filename, string message)
{
TextWriter tw = new StreamWriter(@"c:\MailLogs\" + filename + ".txt");
tw.WriteLine(message);
tw.Close();
}
So, how do I change the code, so I can write the log after the program actually knows whether the mail was sent or not...
Upvotes: 0
Views: 854
Reputation: 2337
Your code is itself doing so now. If WriteLog()
does write Sent Email to...
, it means mail has been sent else not.
Upvotes: 0
Reputation: 3439
SmtpClient sc = new SmtpClient();
sc.SendCompleted += new SendCompletedEventHandler(SendAsyncCallback);
Upvotes: 0
Reputation: 5119
if you execute the line client.Send(mail);
which is not async and it does not throw an Exception it means that the mail has been sent.
Whether it is delivered or not you will not be able to see as that is handled by your smtp server and as far as I know the SmtpClient does not support an event for that.
Upvotes: 1