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

使用C#代码向多个用户发送电子邮件,c#,asp.net,email,gmail,C#,Asp.net,Email,Gmail,早上好,朋友们。。。 我一直在开发一个控制台应用程序,试图向多个用户发送电子邮件。这里我使用一个字符串数组来存储地址。但每次我执行代码时,都会导致错误。需要你的帮助吗 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

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

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”的数组分配给字符串var“to”,所以这是在创建错误。 有谁能告诉我将多个字符串分配给单个字符串变量的最简单方法吗

“指定的字符串不是电子邮件地址所需的格式。”一旦我的控件转到此块执行,我就会在catch块中收到此错误

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

为什么不将
的类型更改为
字符串[]
然后执行以下操作:

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[]”。这是因为:

ToString方法的默认实现返回完整的 对象类型的限定名称

这将为您提供您想要的结果:

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

@拉杰什:你在这条线上遇到了问题:

string From = "your_gmail_id"; // it should be your@gmail.com
请查收并回复

@拉杰什:更换后,如果您有任何进一步的错误,请张贴在这里

下面是完整的更新代码。请查找我所做的更改的//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;
            }
        }
    }
}
使用系统;
使用System.IO;
使用System.Web;
使用System.Linq;
使用System.Net.Mail;
使用System.Net.Mime;
命名空间OracleEntityFrameworkProject
{
类发送电子邮件
{
静态void Main(字符串[]参数)
{
SendingEmail objProgram=新建SendingEmail();
字符串From=”your@gmail_id“;//改变
字符串设置为=”“;//更改
字符串[]Recepeint={”abc@gmail.com;", "efg@gmail.com;", "hij@gmail.com;" };
for(int i=0;i