user4387564
user4387564

Reputation:

Send Email to Multiple User using C# code

Good Morning Friends... I have been working on a Console Application where i'm trying to send Email to multiple user. Here i'm using a array of string to store To address. But everytime i execute my code, it leads me to an error. Need your help

using System;
using System.IO;
using System.Web;
using System.Linq; 
using System.Net.Mail;
using System.Net.Mime;  

namespace Send
{
class Program
{
    static void Main(string[] args)
    {
        Program objProgram = new Program();
        string From = "your_gmail_id";

        string[] Recepeint = { "[email protected];", "[email protected];", "[email protected];" };
        string To = Convert.ToString(Recepeint);

        string Bcc = "[email protected]";

        string Cc = "[email protected]";
        string Subject = "Test";
        string Body = "Hello... This is a Testing Message";
        string strDisplayName = "ABC";
        objProgram.fnSendMailMessage(From, To, Bcc, Cc, Subject, Body, strDisplayName);
        Console.ReadLine();
    }

    // To Send Mail To User
    private bool fnSendMailMessage(string From, string To, string Bcc, string Cc, string Subject, string Body, string strDisplayName = "")
    { 
        try
        {
            // Instantiate a new instance of MailMessage 
            MailMessage mMailMessage = new MailMessage();

            // Set the sender address of the mail message
            mMailMessage.From = new MailAddress(From, strDisplayName);
            foreach (string strRecp in To.Split(','))
            {
                // Set the recepient address of the mail message
                mMailMessage.To.Add(new MailAddress(strRecp));
            }

            // Check if the bcc value is null or an empty string
            if ((!(Bcc == null) && (Bcc != String.Empty)))
            {
                foreach (string strBcc in Bcc.Split(','))
                {
                    // Set the Bcc address of the mail message
                    mMailMessage.Bcc.Add(new MailAddress(strBcc));
                }
            }

            // Check if the cc value is null or an empty value
            if ((!(Cc == null) && (Cc != String.Empty)))
            {
                foreach (string strCc in Cc.Split(','))
                {
                    // Set the CC address of the mail message
                    mMailMessage.CC.Add(new MailAddress(strCc));
                }
            }

            // Set the subject of the mail message
            mMailMessage.Subject = Subject;

            // Code to send Single attachments
            FileStream fs = new FileStream(@"D:\abc-xyz\abc\Links.txt", FileMode.Open, FileAccess.Read);
            Attachment a = new Attachment(fs, "Links.txt", MediaTypeNames.Application.Octet);
            mMailMessage.Attachments.Add(a);

            // Code to send Multiple attachments
            mMailMessage.Attachments.Add(new Attachment(@"C:\Users\abc\Desktop\SPS.txt"));
            mMailMessage.Attachments.Add(new Attachment(@"D:\abc-xyz\UseFull-Links\How to send an Email using C# – complete features.txt"));

            // Secify the format of the body as HTML
            mMailMessage.IsBodyHtml = true;
            //string path = (System.AppDomain.CurrentDomain + "ClientBin\\Images\\ELearningBanner.jpg");

            // To create an embedded image you will need to first create a Html formatted AlternateView. 
            // Within that alternate view you create an  tag, that points to the ContentId (CID) of the LinkedResource. 
            // You then create a LinkedResource object and add it to the AlternateView's LinkedResources collection.
            LinkedResource logo = new LinkedResource(@"C:\Users\abc\Desktop\Send\images.jpg", MediaTypeNames.Image.Jpeg); //It is mainly used for creating embedded images
            logo.ContentId = "Logo";
            AlternateView altView = AlternateView.CreateAlternateViewFromString(Body, null, MediaTypeNames.Text.Html);
            altView.LinkedResources.Add(logo);
            mMailMessage.AlternateViews.Add(altView);

            // Set the priority of the mail message to normal
            mMailMessage.Priority = MailPriority.Normal;

            // Instantiate a new instance of SmtpClient
            SmtpClient mSmtpClient = new SmtpClient();
            mSmtpClient.Host = "smtp.gmail.com";
            mSmtpClient.EnableSsl = true;
            mSmtpClient.Credentials = new System.Net.NetworkCredential("Your_Id", "Your_Password");
            mSmtpClient.Port = 587;

            // Send the mail message
            mSmtpClient.Send(mMailMessage);
            Console.WriteLine("SuccessFully Sent"); 
            return true;
        }
        catch (Exception ex)
        {
            Console.WriteLine("Failed to Send"+ex);                
            return false;
        } 
    }
}

}

Actually main error is that i am trying to assign Array of string "Recepient" to string var "To", so this is creating error. Can anyone tell me any easiest way of assigning Multiple string to a single string variable.

"The specified string is not in the form required for an e-mail address." I'm getting this error in catch block as soon as my control goes to this block for execution

foreach (string strRecp in To.Split(','))
                {
                    // Set the recepient address of the mail message
                    mMailMessage.To.Add(new MailAddress(strRecp));
                }

Upvotes: 0

Views: 2909

Answers (2)

Sandeep Kushwah
Sandeep Kushwah

Reputation: 592

@Rajesh : You got problem at this line :

string From = "your_gmail_id"; // it should be [email protected]

Please check and reply.

@Rajesh : After replacing it if you got any further errors please post it here.

Here is the complete updated code. Please find //change for the changes I have done.

using System;
using System.IO;
using System.Web;
using System.Linq; 
using System.Net.Mail;
using System.Net.Mime;

namespace OracleEntityFrameworkProject
{
    class SendingEmail
    {
        static void Main(string[] args)
        {
            SendingEmail objProgram = new SendingEmail();
            string From = "your@gmail_id"; //change
            string To = ""; //change
            string[] Recepeint = { "[email protected];", "[email protected];", "[email protected];" };

            for (int i = 0; i < Recepeint.Length; i++) //change
            {//change
                To += Recepeint[i];//change
            }//change


            //string To = Convert.ToString(Recepeint);

            string Bcc = "[email protected]";

            string Cc = "[email protected]";
            string Subject = "Test";
            string Body = "Hello... This is a Testing Message";
            string strDisplayName = "ABC";
            objProgram.fnSendMailMessage(From, To, Bcc, Cc, Subject, Body, strDisplayName);
            Console.ReadLine();
        }

        // To Send Mail To User
        private bool fnSendMailMessage(string From, string To, string Bcc, string Cc, string Subject, string Body, string strDisplayName = "")
        {
            try
            {
                // Instantiate a new instance of MailMessage 
                MailMessage mMailMessage = new MailMessage();

                // Set the sender address of the mail message
                mMailMessage.From = new MailAddress(From, strDisplayName);
                foreach (string strRecp in To.Split(new [] {";"}, StringSplitOptions.RemoveEmptyEntries))//change
                {
                    // Set the recepient address of the mail message
                    mMailMessage.To.Add(new MailAddress(strRecp));
                }

                // Check if the bcc value is null or an empty string
                if ((!(Bcc == null) && (Bcc != String.Empty)))
                {
                    foreach (string strBcc in Bcc.Split(','))
                    {
                        // Set the Bcc address of the mail message
                        mMailMessage.Bcc.Add(new MailAddress(strBcc));
                    }
                }

                // Check if the cc value is null or an empty value
                if ((!(Cc == null) && (Cc != String.Empty)))
                {
                    foreach (string strCc in Cc.Split(','))
                    {
                        // Set the CC address of the mail message
                        mMailMessage.CC.Add(new MailAddress(strCc));
                    }
                }

                // Set the subject of the mail message
                mMailMessage.Subject = Subject;

                // Code to send Single attachments
                FileStream fs = new FileStream(@"D:\abc-xyz\abc\Links.txt", FileMode.Open, FileAccess.Read);
                Attachment a = new Attachment(fs, "Links.txt", MediaTypeNames.Application.Octet);
                mMailMessage.Attachments.Add(a);

                // Code to send Multiple attachments
                mMailMessage.Attachments.Add(new Attachment(@"C:\Users\abc\Desktop\SPS.txt"));
                mMailMessage.Attachments.Add(new Attachment(@"D:\abc-xyz\UseFull-Links\How to send an Email using C# – complete features.txt"));

                // Secify the format of the body as HTML
                mMailMessage.IsBodyHtml = true;
                //string path = (System.AppDomain.CurrentDomain + "ClientBin\\Images\\ELearningBanner.jpg");

                // To create an embedded image you will need to first create a Html formatted AlternateView. 
                // Within that alternate view you create an  tag, that points to the ContentId (CID) of the LinkedResource. 
                // You then create a LinkedResource object and add it to the AlternateView's LinkedResources collection.
                LinkedResource logo = new LinkedResource(@"C:\Users\abc\Desktop\Send\images.jpg", MediaTypeNames.Image.Jpeg); //It is mainly used for creating embedded images
                logo.ContentId = "Logo";
                AlternateView altView = AlternateView.CreateAlternateViewFromString(Body, null, MediaTypeNames.Text.Html);
                altView.LinkedResources.Add(logo);
                mMailMessage.AlternateViews.Add(altView);

                // Set the priority of the mail message to normal
                mMailMessage.Priority = MailPriority.Normal;

                // Instantiate a new instance of SmtpClient
                SmtpClient mSmtpClient = new SmtpClient();
                mSmtpClient.Host = "smtp.gmail.com";
                mSmtpClient.EnableSsl = true;
                mSmtpClient.Credentials = new System.Net.NetworkCredential("Your_Id", "Your_Password");
                mSmtpClient.Port = 587;

                // Send the mail message
                mSmtpClient.Send(mMailMessage);
                Console.WriteLine("SuccessFully Sent");
                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine("Failed to Send" + ex);
                return false;
            }
        }
    }
}

Upvotes: 1

RagtimeWilly
RagtimeWilly

Reputation: 5445

Why not change the type of To to string[] then do:

foreach (var email in To))
{
    mailMessage.To.Add(new MailAddress(email));    
}

Also, you'll need to remove the semi-colons from address. So two lines in Main would change to:

static void Main(string[] args)
{
    // ...

    string[] Recepeint = { "[email protected]", "[email protected]", "[email protected]" };

    // ...

    objProgram.fnSendMailMessage(From, Recepeint, Bcc, Cc, Subject, Body, strDisplayName);
}

The reason your code is breaking at the moment is the result of string To = Convert.ToString(Recepeint) is going to be "System.String[]". This is because:

The default implementation of the ToString method returns the fully qualified name of the type of the Object.

This will give you the result you were looking for:

var To = string.Join(",", Recepeint);

Upvotes: 1

Related Questions