使用C#发送电子邮件

Meg*_*yte 46 c# email

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

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

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

提前致谢.

spl*_*tne 73

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

您可以在此处找到MSDN文档.

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

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;
}
Run Code Online (Sandbox Code Playgroud)

  • NetworkCredential类已重载.如果提供空构造函数,它将使用当前用户创建实例.或者,您也可以加密用户名和密码并将其存储在外部.它还取决于您设置邮件服务器的方式.您可以在localhost上设置SMTP服务器,并允许它作为环回地址的中继,以便您可以在不使用凭据的情况下发送电子邮件.我们做后者.它轻巧,简单,不需要存储密码(因为任何人都可以从环回地址中继 - 这也意味着IIS可以). (5认同)
  • 您还可以在配置文件中使用`<system.net> <mailSettings>`配置所有这些.我一直用它来开发时将邮件发送到目录,然后在准备好上线时将其切换为真实发送. (3认同)
  • 有哪些替代方法可以将密码直接嵌入到代码中? (2认同)
  • [MSDN](https://learn.microsoft.com/en-us/dotnet/api/system.net.mail.smtpclient) 的重要说明:&lt;br/&gt; - SmtpClient 类没有 Finalize 方法,因此应用程序必须调用“Dispose”来显式释放资源。- SmtpClient 类型现已过时。我们不建议您使用 SmtpClient 类进行新开发,因为 SmtpClient 不支持许多现代协议。 (2认同)

小智 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);
            }
        }
    }   
}
Run Code Online (Sandbox Code Playgroud)

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

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

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


mis*_*ghi 9

码:

using System.Net.Mail

new SmtpClient("smtp.server.com", 25).send("from@email.com", 
                                           "to@email.com", 
                                           "subject", 
                                           "body");
Run Code Online (Sandbox Code Playgroud)

群发电子邮件:

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

解决方案:

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

  • 出于我的简单目的,您的回答效果很好。两行代码而不是20行! (2认同)

Art*_*jev 5

2023 年 4 月更新:

现在推荐的库是Mailkit.

using MailKit.Net.Smtp;
using MimeKit;

var message = new MimeMessage();
message.From.Add(new MailboxAddress(name: "John Doe", address: "joe@inbox.test"));
message.To.Add(new MailboxAddress(name: "Bruce Williams", address: "bruce@inbox.test"));
message.Subject = "Test subject";

message.Body = new TextPart("plain")
{
    Text = "Test body"
};

using (var client = new SmtpClient())
{
    client.Connect(host: "mail.inbox.example", port: 587, useSsl: true);
    client.Authenticate(userName: "test", password: "test");
    client.Send(message);
    client.Disconnect(quit: true);
}
Run Code Online (Sandbox Code Playgroud)

System.Net.Mail.SmtpClient .NET 作者不推荐

MailKit的作者还说:

对于 SMTP,大多数开发人员使用 System.Net.Mail.SmtpClient,它或多或少满足了他们的需求,因此可能在他们的需求列表中不是很重要。然而,如果需要跨平台支持或者开发人员希望能够在通过 SMTP 发送 MIME 消息之前保存和重新加载 MIME 消息,那么 MailKit 中包含的 SmtpClient 实现是一个更好的选择。MailKit 的 SmtpClient 还支持 PIPELINING,这应该可以提高发送消息的性能(尽管可能不是很明显)。