使用 C# 代码向多个用户发送电子邮件

Send Email to Multiple User using C# code

朋友们早上好... 我一直在开发一个控制台应用程序,我试图在其中向多个用户发送电子邮件。这里我使用一个字符串数组来存储 To 地址。但是每次我执行我的代码时,它都会导致我出错。需要你的帮助

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 = { "abc@gmail.com;", "efg@gmail.com;", "hij@gmail.com;" };
        string To = Convert.ToString(Recepeint);

        string Bcc = "klm@gmail.com";

        string Cc = "xyz@gmail.com";
        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;
        } 
    }
}

}

实际上主要错误是我试图将字符串数组 "Recepient" 分配给字符串变量 "To",因此这是一个错误。 谁能告诉我将多个字符串分配给单个字符串变量的最简单方法。

"The specified string is not in the form required for an e-mail address." 当我的控制转到这个块执行时,我在 catch 块中收到这个错误

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

为什么不将 To 的类型更改为 string[] 然后执行:

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

另外,您需要删除地址中的分号。因此 Main 中的两行将更改为:

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

    string[] Recepeint = { "abc@gmail.com", "efg@gmail.com", "hij@gmail.com" };

    // ...

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

您的代码目前出错的原因是 string To = Convert.ToString(Recepeint) 的结果将是 "System.String[]"。这是因为:

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

这会给你想要的结果:

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

@Rajesh:你在这一行遇到了问题:

string From = "your_gmail_id"; // it should be your@gmail.com

请查看并回复。

@Rajesh:替换后,如果您还有任何错误,请在此处 post。

这是完整的更新代码。请找到 //change 我所做的更改。

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 = { "abc@gmail.com;", "efg@gmail.com;", "hij@gmail.com;" };

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


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

            string Bcc = "klm@gmail.com";

            string Cc = "xyz@gmail.com";
            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;
            }
        }
    }
}