使用C#发送电子邮件

时间:2009-01-16 08:52:09

标签: c# email

我需要通过我的C#app发送电子邮件。

我来自VB 6背景,并且在MAPI控件方面有很多不好的经历。 首先,MAPI不支持HTML电子邮件,其次,所有电子邮件都发送到我的默认邮件发件箱。所以我仍然需要点击发送接收。

如果我需要发送批量html身体邮件(100 - 200),那么在C#中执行此操作的最佳方式是什么?

提前致谢。

12 个答案:

答案 0 :(得分:71)

您可以使用.NET框架的 System.Net.Mail.MailMessage 类。

您可以找到MSDN documentation here

这是一个简单的示例(代码段):

using System.Net;
using System.Net.Mail;
using System.Net.Mime;

...
try
{

   SmtpClient mySmtpClient = new SmtpClient("my.smtp.exampleserver.net");

    // set smtp-client with basicAuthentication
    mySmtpClient.UseDefaultCredentials = false;
   System.Net.NetworkCredential basicAuthenticationInfo = new
      System.Net.NetworkCredential("username", "password");
   mySmtpClient.Credentials = basicAuthenticationInfo;

   // add from,to mailaddresses
   MailAddress from = new MailAddress("test@example.com", "TestFromName");
   MailAddress to = new MailAddress("test2@example.com", "TestToName");
   MailMessage myMail = new System.Net.Mail.MailMessage(from, to);

   // add ReplyTo
   MailAddress replyto = new MailAddress("reply@example.com");
   myMail.ReplyToList.Add(replyTo);

   // set subject and encoding
   myMail.Subject = "Test message";
   myMail.SubjectEncoding = System.Text.Encoding.UTF8;

   // set body-message and encoding
   myMail.Body = "<b>Test Mail</b><br>using <b>HTML</b>.";
   myMail.BodyEncoding = System.Text.Encoding.UTF8;
   // text or html
   myMail.IsBodyHtml = true;

   mySmtpClient.Send(myMail);
}

catch (SmtpException ex)
{
  throw new ApplicationException
    ("SmtpException has occured: " + ex.Message);
}
catch (Exception ex)
{
   throw ex;
}

答案 1 :(得分:16)

以更快的方式发送批量电子邮件的最佳方式是使用threads.I已编写此控制台应用程序以发送批量电子邮件。我已通过创建两个线程池将批量电子邮件ID分成两批。

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Net.Mail;

namespace ConsoleApplication1
{
    public class SendMail 
    {
        string[] NameArray = new string[10] { "Recipient 1", 
                                              "Recipient 2",
                                              "Recipient 3",
                                              "Recipient 4", 
                                              "Recipient 5", 
                                              "Recipient 6", 
                                              "Recipient 7", 
                                              "Recipient 8",
                                              "Recipient 9",
                                              "Recipient 10"
                                            };        

        public SendMail(int i, ManualResetEvent doneEvent)
        {
            Console.WriteLine("Started sending mail process for {0} - ", NameArray[i].ToString() + " at " + System.DateTime.Now.ToString());
            Console.WriteLine("");
            SmtpClient mailClient = new SmtpClient();
            mailClient.Host = Your host name;
            mailClient.UseDefaultCredentials = true;
            mailClient.Port = Your mail server port number; // try with default port no.25

            MailMessage mailMessage = new MailMessage(FromAddress,ToAddress);//replace the address value
            mailMessage.Subject = "Testing Bulk mail application";
            mailMessage.Body = NameArray[i].ToString();
            mailMessage.IsBodyHtml = true;
            mailClient.Send(mailMessage);
            Console.WriteLine("Mail Sent succesfully for {0} - ",NameArray[i].ToString() + " at " + System.DateTime.Now.ToString());
            Console.WriteLine("");

            _doneEvent = doneEvent;
        }

        public void ThreadPoolCallback(Object threadContext)
        {
            int threadIndex = (int)threadContext;
            Console.WriteLine("Thread process completed for {0} ...",threadIndex.ToString() + "at" +  System.DateTime.Now.ToString());
            _doneEvent.Set();
        }      

        private ManualResetEvent _doneEvent;
    }


    public class Program
    {
        static int TotalMailCount, Mailcount, AddCount, Counter, i, AssignI;  
        static void Main(string[] args)
        {
            TotalMailCount = 10;
            Mailcount = TotalMailCount / 2;
            AddCount = Mailcount;
            InitiateThreads();                     

            Thread.Sleep(100000);
        }

       static void InitiateThreads()
       {
            //One event is used for sending mails for each person email id as batch
           ManualResetEvent[] doneEvents = new ManualResetEvent[Mailcount];

            // Configure and launch threads using ThreadPool:
            Console.WriteLine("Launching thread Pool tasks...");

            for (i = AssignI; i < Mailcount; i++)            
            {
                doneEvents[i] = new ManualResetEvent(false);
                SendMail SRM_mail = new SendMail(i, doneEvents[i]);
                ThreadPool.QueueUserWorkItem(SRM_mail.ThreadPoolCallback, i);
            }

            Thread.Sleep(10000);

            // Wait for all threads in pool to calculation...
            //try
            //{
            // //   WaitHandle.WaitAll(doneEvents);
            //}
            //catch(Exception e)
            //{
            //    Console.WriteLine(e.ToString());   
            //}

            Console.WriteLine("All mails are sent in this thread pool.");
            Counter = Counter+1;
            Console.WriteLine("Please wait while we check for the next thread pool queue");
            Thread.Sleep(5000);
            CheckBatchMailProcess();            
        }

        static  void CheckBatchMailProcess()
        {

            if (Counter < 2)
            {
                Mailcount = Mailcount + AddCount;
                AssignI = Mailcount - AddCount;
                Console.WriteLine("Starting the Next thread Pool");

                Thread.Sleep(5000);
                InitiateThreads();
            }

            else
            {
                Console.WriteLine("No thread pools to start - exiting the batch mail application");
                Thread.Sleep(1000);
                Environment.Exit(0);
            }
        }
    }   
}

我已在数组列表中为样本定义了10个接收者。它将创建两批电子邮件来创建两个线程池来发送邮件。您也可以从数据库中选择详细信息。

您可以通过在控制台应用程序中复制和粘贴它来使用此代码。(替换program.cs文件)。然后该应用程序即可使用。

我希望这可以帮助你:)。

答案 2 :(得分:7)

<强>代码:

using System.Net.Mail

new SmtpClient("smtp.server.com", 25).send("from@email.com", 
                                           "to@email.com", 
                                           "subject", 
                                           "body");

群发电子邮件:

SMTP服务器通常对帽子可以同时处理的连接数量有限制,如果您尝试发送数百封电子邮件,您的应用程序可能会显示无响应。

解决方案:

  • 如果要构建WinForm,请使用BackgroundWorker处理队列。
  • 如果您使用的是IIS SMTP服务器或具有发件箱文件夹的SMTP服务器,则可以使用SmtpClient()。PickupDirectoryLocation =“c:/ smtp / outboxFolder”;这将使您的系统保持响应。
  • 如果您没有使用本地SMTP服务器而不是构建系统服务来使用Filewatcher监视forlder,那么将处理您放入的任何电子邮件。

答案 3 :(得分:4)

.NET框架有一些内置类,允许您通过应用程序发送电子邮件。

您应该查看System.Net.Mail命名空间,您可以在其中找到MailMessage和SmtpClient类。 您可以将MailMessage类的BodyFormat设置为MailFormat.Html。

如果您使用MailMessage类的AlternateViews属性,它也可能会有所帮助,以便您可以提供邮件的纯文本版本,以便不支持HTML的客户端可以读取它。 / p>

http://msdn.microsoft.com/en-us/library/system.net.mail.mailmessage.alternateviews.aspx

答案 4 :(得分:3)

您可以使用SMTP或CDO发送电子邮件

使用SMTP:

mail.From = new MailAddress("your_email_address@gmail.com");
mail.To.Add("to_address");
mail.Subject = "Test Mail";
mail.Body = "This is for testing SMTP mail from GMAIL";

SmtpServer.Port = 587;
SmtpServer.Credentials = new System.Net.NetworkCredential("username", "password");
SmtpServer.EnableSsl = true;

来源:C# SMTP Email

CDO.Message oMsg = new CDO.Message();
CDO.IConfiguration iConfg;
iConfg = oMsg.Configuration;
ADODB.Fields oFields;
oFields = iConfg.Fields;
ADODB.Field oField = oFields["http://schemas.microsoft.com/cdo/configuration/sendusing"];
oFields.Update();
oMsg.Subject = "Test CDO";
oMsg.From = "from_address";
oMsg.To = "to_address";
oMsg.TextBody = "CDO Mail test";
oMsg.Send();

来源:C# CDO Email

的Manly

答案 5 :(得分:2)

我强烈推荐aspNetEmail库:http://www.aspnetemail.com/

如果您的需求只是基本的,System.Net.Mail会让您到达某个地方,但如果您遇到麻烦,请查看aspNetEmail。它节省了我很多时间,而且我知道其他发明者也发誓!

答案 6 :(得分:1)

使用名称空间System.Net.Mail。 Here is a link to the MSDN page

您可以使用SmtpClient类发送电子邮件。

我解释了代码示例,因此请查看MSDN以获取详细信息。

MailMessage message = new MailMessage(
   "fromemail@contoso.com",
   "toemail@contoso.com",
   "Subject goes here",
   "Body goes here");

SmtpClient client = new SmtpClient(server);
client.Send(message);

发送许多电子邮件的最佳方法是将这样的内容放入forloop并发送出去!

答案 7 :(得分:0)

查看FluentEmail库。 我在博客上写了here

你有一个很好的,流畅的api满足你的需求:

Email.FromDefault()
 .To("you@domain.com")
 .Subject("New order has arrived!")
 .Body("The order details are…")  
 .Send();

答案 8 :(得分:0)

让我们作一些完整的解决方案:)。也许它也可以提供帮助。 这是一种向多个电子邮件地址发送一个电子邮件内容和一个附件(或不附加附件)的解决方案。当然也可以只发送一封电子邮件。结果是具有数据的列表对象,什么可以,什么不能。

namespace SmtpSendingEmialMessage
{ 
    public class EmailSetupData
    {
        public string EmailFrom { get; set; }
        public string EmailUserName { get; set; }
        public string EmailPassword { get; set; }
        public string EmailSmtpServerName { get; set; }
        public int EmailSmtpPortNumber { get; set; }
        public Boolean SSLActive { get; set; } = false;
    }

    public class SendingResultData
    {
        public string SendingEmailAddress { get; set; }
        public string SendingEmailSubject { get; set; }
        public DateTime SendingDateTime { get; set; }
        public Boolean SendingEmailSuccess { get; set; }
        public string SendingEmailMessage { get; set; }
    }
    public class OneRecData
    {
        public string RecEmailAddress { get; set; } = "";
        public string RecEmailSubject { get; set; } = "";
    }


    public class SendingProcess
    {
        public string EmailCommonSubjectOptional { get; set; } = "";
        private EmailSetupData EmailSetupParam { get; set; }
        private List<OneRecData> RecDataList { get; set; }
        private string EmailBodyContent { get; set; }
        private Boolean IsEmailBodyHtml { get; set; }
        private string EmailAttachFilePath { get; set; }

        public SendingProcess(List<OneRecData> MyRecDataList, String MyEmailTextContent, String MyEmailAttachFilePath, EmailSetupData MyEmailSetupParam, Boolean EmailBodyHtml)
        {
            RecDataList = MyRecDataList;
            EmailBodyContent = MyEmailTextContent;
            EmailAttachFilePath = MyEmailAttachFilePath;
            EmailSetupParam = MyEmailSetupParam;
            IsEmailBodyHtml = EmailBodyHtml;
        }

        public List<SendingResultData> SendAll()
        {
            List<SendingResultData> MyResList = new List<SendingResultData>();
            foreach (var js in RecDataList)
            {
                using (System.Net.Mail.MailMessage MyMes = new System.Net.Mail.MailMessage())
                {
                    DateTime SadaJe = DateTime.Now;
                    Boolean IsOK = true;
                    String MySendingResultMessage = "Sending OK";

                    String MessageSubject = EmailCommonSubjectOptional;
                    if (MessageSubject == "")
                    {
                        MessageSubject = js.RecEmailSubject;
                    }

                    try
                    {

                        System.Net.Mail.MailAddress MySenderAdd = new System.Net.Mail.MailAddress(js.RecEmailAddress);
                        MyMes.To.Add(MySenderAdd);
                        MyMes.Subject = MessageSubject;
                        MyMes.Body = EmailBodyContent;
                        MyMes.Sender = new System.Net.Mail.MailAddress(EmailSetupParam.EmailFrom);
                        MyMes.ReplyToList.Add(MySenderAdd);
                        MyMes.IsBodyHtml = IsEmailBodyHtml;

                    }
                    catch(Exception ex)
                    {
                        IsOK = false;
                        MySendingResultMessage ="Sender or receiver Email address error." +  ex.Message;
                    }

                    if (IsOK == true)
                    {
                        try
                        {
                            if (EmailAttachFilePath != null)
                            {
                                if (EmailAttachFilePath.Length > 5)
                                {
                                    MyMes.Attachments.Add(new System.Net.Mail.Attachment(EmailAttachFilePath));
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            IsOK = false;
                            MySendingResultMessage ="Emial attach error. " +  ex.Message;
                        }

                        if (IsOK == true)
                        {
                            using (System.Net.Mail.SmtpClient MyCl = new System.Net.Mail.SmtpClient())
                            {
                                MyCl.EnableSsl = EmailSetupParam.SSLActive;
                                MyCl.Host = EmailSetupParam.EmailSmtpServerName;
                                MyCl.Port = EmailSetupParam.EmailSmtpPortNumber;
                                try
                                {
                                    MyCl.Credentials = new System.Net.NetworkCredential(EmailSetupParam.EmailUserName, EmailSetupParam.EmailPassword);
                                }
                                catch (Exception ex)
                                {
                                    IsOK = false;
                                    MySendingResultMessage = "Emial credential error. " + ex.Message;
                                }

                                if (IsOK == true)
                                {
                                    try
                                    {
                                        MyCl.Send(MyMes);
                                    }
                                    catch (Exception ex)
                                    {
                                        IsOK = false;
                                        MySendingResultMessage = "Emial sending error. " + ex.Message;
                                    }
                                }
                            }
                        }
                    }

                    MyResList.Add(new SendingResultData
                    {
                            SendingDateTime = SadaJe,
                            SendingEmailAddress = js.RecEmailAddress,
                            SendingEmailMessage = MySendingResultMessage,
                            SendingEmailSubject = js.RecEmailSubject,
                            SendingEmailSuccess = IsOK
                    });
                }

            }
            return MyResList;
        }
    }

}

答案 9 :(得分:0)

您可以使用Mailkit。MailKit是一个基于MimeKit并针对移动设备进行了优化的开源跨平台.NET邮件客户端库。

它具有比System.Net.Mail更好的更多高级功能

  • 完全可取消的Pop3Client,它支持STLS,UIDL,APOP,PIPELINING,UTF8和LANG。客户端的排序和线程化 消息(序数主题和Jamie Zawinski线程 算法)。
  • 触及网络的所有方法的异步版本。
  • 通过MimeKit的
  • S / MIME,OpenPGP和DKIM签名支持。
  • 通过MimeKit支持Microsoft TNEF。

    您可以从here下载。

在此示例中,您可以发送邮件

            MimeMessage mailMessage = new MimeMessage();
            mailMessage.From.Add(new MailboxAddress(senderName, sender@address.com));
            mailMessage.Sender = new MailboxAddress(senderName, sender@address.com);
            mailMessage.To.Add(new MailboxAddress(emailid, emailid));
            mailMessage.Subject = subject;
            mailMessage.ReplyTo.Add(new MailboxAddress(replyToAddress));
            mailMessage.Subject = subject;
            var builder = new BodyBuilder();
            builder.TextBody = "Hello There";            
            try
            {
                using (var smtpClient = new SmtpClient())
                {
                    smtpClient.Connect("HostName", "Port", MailKit.Security.SecureSocketOptions.None);
                    smtpClient.Authenticate("user@name.com", "password");

                    smtpClient.Send(mailMessage);
                    Console.WriteLine("Success");
                }
            }
            catch (SmtpCommandException ex)
            {
                Console.WriteLine(ex.ToString());              
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());                
            }

答案 10 :(得分:0)

下面的附加解决方案在本地计算机和服务器上工作。

     public static string SendMail(string bodyContent)
    {
        string sendMail = "";
        try
        {

            string fromEmail = "from@gmail.com";
            MailMessage mailMessage = new MailMessage(fromEmail, "to@gmail.com", "Subject", body);
            mailMessage.IsBodyHtml = true;
            SmtpClient smtpClient = new SmtpClient("smtp.gmail.com", 587);
            smtpClient.EnableSsl = true;
            smtpClient.UseDefaultCredentials = false;
            smtpClient.Credentials = new NetworkCredential(fromEmail, frompassword);
            smtpClient.Send(mailMessage);
        }
        catch (Exception ex)
        {
            sendMail = ex.Message.ToString();
            Console.WriteLine(ex.ToString());
        }
        return sendMail;
    }

答案 11 :(得分:0)

   public string sendEmail(string mail,string subject, string body)
   {
       try
       {
           MailMessage message = new MailMessage();
           SmtpClient smtp = new SmtpClient();
           message.From = new MailAddress("example@gmail.com");
           message.To.Add(new MailAddress(mail));
           message.Subject = subject;
           message.IsBodyHtml = true; //to make message body as html  
           message.Body = body;
           smtp.Port = 587;
           smtp.Host = "smtp.gmail.com"; //for gmail host  
           smtp.EnableSsl = true;
           smtp.UseDefaultCredentials = false;
           smtp.Credentials = new NetworkCredential("example@gmail.com", "password");
           smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
           smtp.Send(message);
           return "success";
       }
       catch (Exception e) {
           return e.Message;
       }
   }‏