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

时间:2015-03-19 05:44:35

标签: c# asp.net email gmail

早上好朋友...... 我一直在研究控制台应用程序,我正在尝试向多个用户发送电子邮件。这里我使用一个字符串数组来存储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”的数组分配给字符串var“To”,所以这就是创建错误。 任何人都可以告诉我任何最简单的方法将多个字符串分配给单个字符串变量。

“指定的字符串不是电子邮件地址所需的格式。”一旦我的控件转到此块执行

,我就会在catch块中收到此错误
foreach (string strRecp in To.Split(','))
                {
                    // Set the recepient address of the mail message
                    mMailMessage.To.Add(new MailAddress(strRecp));
                }

2 个答案:

答案 0 :(得分:1)

为什么不将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 []"。这是因为:

  

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

这将为您提供您正在寻找的结果:

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

答案 1 :(得分:1)

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

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

请检查并回复。

@Rajesh:更换后如果您有任何进一步的错误,请在此处发布。

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

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;
            }
        }
    }
}