小编典典

使用C#发送电子邮件

c#

我需要通过C#应用发送电子邮件。

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

如果我需要发送大量html正文电子邮件(100-200),那么在C#中最好的方法是什么?

提前致谢。


阅读 406

收藏
2020-05-19

共1个答案

小编典典

您可以使用.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;
}
2020-05-19