none
I want to send email & to get list of all emails which are failed to sent RRS feed

  • Question

  • I want to create a project in which I want to send emails and after sending there may be some emails which are not send or may be email address is wrong so I want to get list of all email address which are not send...yet so in future i can resend those emails..
    Thursday, February 18, 2016 1:15 PM

Answers

  • The following is for sending message and handling errors. The log is a simple example that needs work.

    Some of the Smtp information is taken from app.config where you need to set from, host and port

    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
        <startup> 
            <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
        </startup>
      <system.net>
        <mailSettings>
          <smtp from="Your email address">
            <network host="Your host" port="25" />
          </smtp>
        </mailSettings>
      </system.net>  
    </configuration>

    A reference for System.Configuration will be needed to be added to your project. Note I used one email for from and to so it would be easy to test but you need to alter that to a real to address.

    using System;
    using System.Collections.Generic;
    using System.Configuration;
    using System.Net.Configuration;
    using System.Net.Mail;
    using System.Reflection;
    using System.Threading;
    using System.Threading.Tasks;
    
    namespace Casting_as
    {
        /// <summary>
        /// Used to log to text file
        /// Simple example.
        /// </summary>
        public class Log
        {
            private string fileName = "TODO";
            List<string> entries = new List<string>();
            public Log()
            {
                if (System.IO.File.Exists(fileName))
                {
                    entries.AddRange(System.IO.File.ReadAllLines(fileName));
                }
            }
            public void ErrorEntry(string sender)
            {
                entries.Add($"Failed sending: {sender}");
            }
            public void Save()
            {
                // code to save log entries
            }
        }
        /// <summary>
        /// Send mail 
        /// </summary>
        /// <remarks>
        /// test method would be outside of this class for your app.
        /// </remarks>
        public static class SendMailEx
        {
           
            private static Configuration config;
            private static MailSettingsSectionGroup mailSettings;
            private static string toAddress;
    
            static SendMailEx()
            {
                config = ConfigurationManager.OpenExeConfiguration(Assembly.GetExecutingAssembly().Location);
                mailSettings = (MailSettingsSectionGroup)config.GetSectionGroup("system.net/mailSettings");
            }
            public static async void test()
            {
                using (SmtpClient MailClient = new SmtpClient(mailSettings.Smtp.Network.Host, mailSettings.Smtp.Network.Port))
                {
                    using (MailMessage Mail = new MailMessage() { From = new MailAddress(mailSettings.Smtp.From), Subject = "Test", IsBodyHtml = true, Body = "<p>This <strong>is a</strong> test.</p>" })
                    {
                        toAddress = mailSettings.Smtp.From;
                        Mail.To.Add(new MailAddress(toAddress));
                        await SendMailExAsync(MailClient, Mail);
                    }
                }
            }
            public static Task SendMailExAsync(this SmtpClient @this, MailMessage message, CancellationToken token = default(CancellationToken))
            {
                // use Task.Run to negate SynchronizationContext
                return Task.Run(() => SendMailExImplAsync(@this, message, token));
            }
            private static async Task SendMailExImplAsync(SmtpClient client, MailMessage message, CancellationToken token)
            {
                Log log = new Log();
                token.ThrowIfCancellationRequested();
    
                var tcs = new TaskCompletionSource<bool>();
    
                System.Net.Mail.SendCompletedEventHandler handler = null;
                Action unsubscribe = () => client.SendCompleted -= handler;
    
                handler = async (s, e) =>
                {
                    unsubscribe();
    
                    // a hack to complete the handler asynchronously
                    await Task.Yield();
    
    
                    if (e.UserState != tcs)
                        tcs.TrySetException(new InvalidOperationException("Unexpected UserState"));
                    else if (e.Cancelled)
                        tcs.TrySetCanceled();
                    else if (e.Error != null)
                    {
                        log.ErrorEntry(toAddress);
                        tcs.TrySetException(e.Error);
                    }               
                    else
                        tcs.TrySetResult(true);
                };
    
                client.SendCompleted += handler;
    
                try
                {
                    client.SendAsync(message, tcs);
                    using (token.Register(() => client.SendAsyncCancel(), useSynchronizationContext: false))
                    {
                        await tcs.Task;
                    }
                }
                finally
                {
                    unsubscribe();
                }
            }
        }
    }
    


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites


    Thursday, February 18, 2016 1:57 PM
    Moderator