C# 发邮件例子

我相信这对于使用过C#发邮件的过来人来说,太不屑一顾了,呵呵,我是第一次发现原来我也能写blog的地方,所以急手之急,就随便弄出些文字看看效果再说的哟,
但对于初次使用C#发邮件应该还是有一点帮助的.
费话少说了,看看下面的代码对你有用否?

class SendMailer
    {
        public static void Send(           
            string subject,
            string body,
            MailAttachment[] attach)
        {
             /*
                之所以写成Config.* 的原因我想是这些一般都是写到配置文件中的
               当然你觉得你不会这样的话,可自行修改的
             */
         
            //  MAIL服务器名称或IP都行(比如:smtp.sohu.com)
            string server = Config.GetMailServer();
            // 接收者邮箱 (比如:XXX@sohu.com),这里当然也可以是多个,以;来分开
            string to = Config.GetRecieveAccount();
            // 同时暗送给那些接受者
            string cc = Config.GetOtherRecieveAccount();
            // 注册的帐号 (比如:XXX@sohu.com)
            string from = Config.GetSendMailAccount();
            // 帐号密码
            string pwd = Config.GetSendMailAccountPwd();
            MailMessage mail = new MailMessage();

            mail.From = from;
            mail.To = to;
            mail.Subject = subject;
            mail.Cc = cc;
            mail.Body = body;
            mail.Priority = MailPriority.High;
            // 粘付件
            if (attach != null)
            {
                for (int i = 0; i < attach.Length; ++i)
                {
                    mail.Attachments.Add(attach[i]);
                }
            }
            SmtpMail.SmtpServer = server;
            string user = "";
            // 取得帐号ID
            Regex r = new Regex("(?<account>.*?)@.*");
            Match m = r.Match(from);
            if (m != null)
            {
                user = m.Result("${account}");
            }
            mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1");
            mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", user);
            mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", pwd);
            try
            {
                SmtpMail.Send(mail);
            }
            catch (Exception ex)
            {              
                throw ex;
            }
        }
    }

当然记得要引用相应的命名空间的
using System.Text.RegularExpressions;
using System.Web.Mail;

你是不是说没有此命名空间,别告诉我你不会在VS中添加引用的哟
好了不罗锁了,下班了,回家了.
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值