How TO: 使用 System.Web.Mail 和 Visual C# .NET 以编程方式发送电子邮件 (From MSDN)

概要

本文演示如何使用 System.Web.Mail 在 Visual C#.NET 中发送电子邮件。

更多信息

  1. 启动 Microsoft Visual Studio .NET。在文件 菜单中,单击新建 ,然后单击项目。依次单击Visual C# 项目控制台应用程序 模板,然后单击确定。 默认情况下创建 Class1.cs。
  2. 添加对System.Web.dll 的引用。为此,请执行以下步骤:
    1. 项目 菜单中,单击添加引用
    2. .NET 选项页中,找到System.Web.dll,然后单击选择
    3. 添加引用 对话框中单击确定 接受所做的选择。如果提示您为选定的库生成包装,单击
  3. 在代码窗口中,用以下内容替换整个代码:
    using System;
    using System.Web.Mail;
    
    namespace WebMail
    {
        class Class1
        {
            static void Main(string[] args)
            {
                try 
                {
                    MailMessage oMsg = new MailMessage();
                    // TODO: Replace with sender e-mail address.
                    oMsg.From = "sender@somewhere.com";
                    // TODO: Replace with recipient e-mail address.
                    oMsg.To = "recipient@somewhere.com";
                    oMsg.Subject = "Send Using Web Mail";
                    
                    // SEND IN HTML FORMAT (comment this line to send plain text).
                    oMsg.BodyFormat = MailFormat.Html;
                    
                    // HTML Body (remove HTML tags for plain text).
                    oMsg.Body = "<HTML><BODY><B>Hello World!</B></BODY></HTML>";
                    
                    // ADD AN ATTACHMENT.
                    // TODO: Replace with path to attachment.
                    String sFile = @"C:/temp/Hello.txt";  
                    MailAttachment oAttch = new MailAttachment(sFile, MailEncoding.Base64);
      
                    oMsg.Attachments.Add(oAttch);
    
                    // TODO: Replace with the name of your remote SMTP server.
                    SmtpMail.SmtpServer = "MySMTPServer";
                    SmtpMail.Send(oMsg);
    
                    oMsg = null;
                    oAttch = null;
                }
                catch (Exception e)
                {
                    Console.WriteLine("{0} Exception caught.", e);
                }
            }
        }
    } 
    					

  4. 修改“TODO”处的代码。
  5. 按 F5 键编译并运行程序。
  6. 验证是否已发送和收到电子邮件。

这篇文章中的信息适用于:

  • Microsoft Visual C# .NET (2002)
最近更新:2004-3-25 (1.2)
关键字:kbhowto KB310273
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值