使用 C# 发送电子邮件 [英] Sending E-mail using C#

查看:46
本文介绍了使用 C# 发送电子邮件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要通过我的 C# 应用程序发送电子邮件.

I need to send email via my C# app.

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

I come from a VB 6 background and had a lot of bad experiences with the MAPI control. First of all, MAPI did not support HTML emails and second, all the emails were sent to my default mail outbox. So I still needed to click on send receive.

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

If I needed to send bulk html bodied emails (100 - 200), what would be the best way to do this in C#?

推荐答案

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

You could use the System.Net.Mail.MailMessage class of the .NET framework.

您可以找到 MSDN文档在这里.

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

Here is a simple example (code snippet):

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

这篇关于使用 C# 发送电子邮件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆