none
Reading from StreamReader and send email RRS feed

  • Question

  • Hi All 

    Hoping someone can help. I have a text file which holds email addresses, i want to read the file and then pass the email addresses to send an email. My code complies and runs however the email never arrives. If i change the code to send to my address it works fine

                String[] techemail = new string[10];
                string line;
                try
                {
                    StreamReader sr = new StreamReader(@"\\C:\AAA\TechEmail.txt");
                    line = sr.ReadLine();
                    int i = 0;
    
                    while (line != null)
                    {
                        techemail[i] = line;
                        i -= -1;
                        
                        line = sr.ReadLine();
                    }
    
                    sr.Close();
                    
    
                }
                catch 
                {
    
                }
    As stated above if i change the To.Add(myemail@send.com) it works fine
                        string[] to = techemail;
                        foreach (var m in to)
                        {
                            testtimestamp.To.Add(m);
    
                        }

    What am i missing

    Thanks in advance

    Wednesday, November 27, 2019 5:00 PM

All replies

  • Try doing that twice... Does it do the same thing?

    George Frias - AWWshop, Wiki1978

    Wednesday, November 27, 2019 5:15 PM
  • Can you show the SmtpClient code and of course mask the user name and password.

    Also note if the host is GMail see https://support.google.com/accounts/answer/6010255?hl=en

     

    Please remember to mark the replies as answers if they help and unmarked 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.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    Wednesday, November 27, 2019 6:16 PM
    Moderator
  • Maybe you should exclude unused null elements:

       string [ ] to = techemail;

       foreach( var m in to )

       {

           if( ! string.IsNullOrWhiteSpace( m ) )

           {

              testtimestamp.To.Add( m );

          }

       }

    Make sure that the real file path is valid. Use the debugger and breakpoints to check the contents of variables.



    • Edited by Viorel_MVP Wednesday, November 27, 2019 6:48 PM
    Wednesday, November 27, 2019 6:44 PM
  • Have you verified that it attempts to send emails also to other addesses to that there is not error before that?

    Also for debugging you can use pickup directory so that you can verify if mail are stored in pickup directory then your mail sending at least works so that mails are actually created. See MailMessage PickupDirectoryLocation and DeliveryMethod properties if you want to try that.

    Thursday, November 28, 2019 7:21 AM
  • Hi

    Code below,

    Please note - ive changed some of the code not to show the actually details. The host is an internal address.

                        SmtpClient client = new SmtpClient();
                        client.Port = 25;
                        client.Host = "10.10.10.10";
                        client.DeliveryMethod = SmtpDeliveryMethod.Network;
                        client.UseDefaultCredentials = true;
    
                        MailMessage testtimestamp = new MailMessage();
                        testtimestamp.From = new MailAddress("FromHere@send.com");
    
                        string[] to = techemail;
                        foreach (string m in techemail)
                        {
                   
                                testtimestamp.To.Add(m);
                            
                        }
    
    
                        testtimestamp.Subject = string.Format("Testing");
                        testtimestamp.Body = ("testing sending email");
                        client.Send(testtimestamp);

    Thursday, November 28, 2019 2:41 PM
  • Hi LloydyJ89,

    According to your description, it seems that some mailboxes can receive mail and some cannot.

    I think it might be because different mailboxes may use different protocols, so that caused this problem.

    Best Regards,

    Timon


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.


    Friday, November 29, 2019 10:04 AM
  • ***UPDATE***

    So after doing some digging around and spending a few hours i have managed to read from a text file and send an email in a seperate project. Code Below:

    namespace StreamReaderTest
    {
        class Program
        {
            static void Main(string[] args)
            {
                    SmtpClient client = new SmtpClient();
                    client.Port = 25;
                    client.Host = "10.10.10.10";
                    client.DeliveryMethod = SmtpDeliveryMethod.Network;
                    client.UseDefaultCredentials = true;
    
                    MailMessage testtimestamp = new MailMessage();
                    testtimestamp.From = new MailAddress("Thisisatest@send.com");
    
                    List<String> lst = new List<String>();
                    string[] interArray = new string[6];
                    int counter = 0;
                    string[] stringArray = System.IO.File.ReadAllLines(@"C:\AAA\TechEmail.txt");
                    foreach (string example in stringArray)
                    {
                        lst.Add(example.Trim());
                        interArray[counter] = (example.Trim());
                        counter++;
                        testtimestamp.To.Add(example);
                    }
                         testtimestamp.Subject = string.Format("Testing");
                         testtimestamp.Body = ("testing sending email");
                         client.Send(testtimestamp);
                    }       
                }
            }
        

    However when i try and copy this code into my main project i still do not receive an email. I gather its because of the foreach loop. If i put testtimestamp.To.Add(myemail) outside of the loop it works fine

                using (PowerShell PowershellInstance = PowerShell.Create())
                {
                    PowershellInstance.AddScript("$timeStamp = (get-date).addMinutes(-5); $threats = Get-MpThreatDetection; $filteredthreats =@(); foreach ($thr in $threats){if (($timeStamp - $thr.InitialDetectionTime) -le 0){$filteredthreats += $thr }};" +
                    "foreach ($threat in $filteredthreats){$threat.domainuser, $env:COMPUTERNAME, $threat.InitialDetectionTime, $threat.Resources[0], $threat.ProcessName, $threats.ActionSuccess}");
    
                    Collection<PSObject> PSOutput = PowershellInstance.Invoke();
    
                    int x = PSOutput.Count / 6;
                    for (int i = 1; i <= PSOutput.Count; i = i + 6)
                    {
                        SmtpClient client = new SmtpClient();
                        client.Port = 25;
                        client.Host = "10.10.10.10";
                        client.DeliveryMethod = SmtpDeliveryMethod.Network;
                        client.UseDefaultCredentials = true;
    
                        MailMessage testtimestamp = new MailMessage();
                        testtimestamp.From = new MailAddress("Thisisatest@send.com");
    
                        List<String> lst = new List<String>();
                        string[] interArray = new string[6];
                        int counter = 0;
                        string[] stringArray = System.IO.File.ReadAllLines(@"C:\AAA\TechEmail.txt");
                        foreach (string example in stringArray)
                        {
                            lst.Add(example.Trim());
                            interArray[counter] = (example.Trim());
                            counter++;
                            testtimestamp.To.Add(example);
    
                        }
    
                        //If i put this - email gets sent testtimestamp.To.Add("myemail@.com"); 
                        testtimestamp.Subject = string.Format("Alert - " + PSOutput[i]);
                        testtimestamp.Body = ("User: ") + (PSOutput[i - 1]) + "\r\n" + ("Asset Number: ") + (PSOutput[i]) + "\r\n" + ("Time: ") + (PSOutput[i + 1]) + "\r\n" + ("File Location: ") + (PSOutput[i + 2]) + "\r\n" + ("Process Name: ") + (PSOutput[i + 3]);
                        client.Send(testtimestamp);
                    }
                }
            }
    
        }
    }

    Any help / advice to resolve this would be appreciated 

    Thanks


    • Edited by LloydyJ89 Tuesday, December 3, 2019 2:53 PM edit
    Tuesday, December 3, 2019 11:45 AM
  • You could add a try-catch, use SendCompleted event to troubleshoot as per below which is not a replacement for your code but to show how to use SendCompleted event. Note smtp.SendAsync 2nd parameter is of type object and can be anything, I've used it to integrate the MailMessage as it's not in scope at this point.

    This is not included in the final example but wanted to show that I use a special class to inspect the MailMessage in SendCompleted.

    var emailMessageContainer = new EmailSniffer();
    
    if (eventArguments.UserState is MailMessage mailMessage)
    {
    
        emailMessageContainer.Inspect((SmtpClient)sender, eventArguments);
    
    }
    else
    {
        emailMessageContainer.Inspect();
    }

    Focus on this code

    using System;
    using System.Collections.Generic;
    using System.Net;
    using System.Net.Mail;
    
    namespace AdapterDesignPattern
    {
        public class Emailer
        {
            public void SendAsync(List<string> sendToList)
            {
                var message = new MailMessage();
                sendToList.ForEach(recipient => message.To.Add(recipient));
    
                message.From = new MailAddress("TODO");
                message.Subject = "TODO";
                message.Body = "TODO";
                message.IsBodyHtml = false;
                var smtp = new SmtpClient("", 25)
                {
                    DeliveryMethod = SmtpDeliveryMethod.Network,
                    Credentials = new NetworkCredential("TODO", "TODO")
                };
    
                smtp.SendCompleted += Smtp_SendCompleted;
                smtp.SendCompleted += (engine, eventArguments) =>
                {
                    smtp.Dispose();
                    message.Dispose();
                };
    
                try
                {
                    smtp.SendAsync(message, message);
                }
                catch (Exception generalException)
                {
                    switch (generalException)
                    {
                        case SmtpFailedRecipientsException _:
                        {
                            // decide how to handle
                            break;
                        }
    
                        case SmtpException smtpException:
                        {
    
                            // decide how to handle
                            break;
                        }
                    }
                }
    
            }
    
            private void Smtp_SendCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
            {
                if (e.Error != null)
                {
                    Console.WriteLine(e.Error.Message);
                }
    
                if (e.Cancelled)
                {
                    Console.WriteLine("Cancelled");
                }
            }
        }
    }
    


    Please remember to mark the replies as answers if they help and unmarked 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.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    Tuesday, December 3, 2019 8:52 PM
    Moderator