C#发送邮件的方法及实例代码

来源:互联网 发布:淘宝模特收费 编辑:程序博客网 时间:2024/05/18 01:42
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Mail;
using System.ComponentModel;
using System.Windows.Forms;
using System.Net;
namespace com.ykmaiz.email
{
    public class Mail
    {
        private string username = "";
        private string password = "";
        private string domain = "";
        public Mail(string username,string password,string domain)
        {
            this.username = username;
            this.password = password;
            this.domain = domain;
        }
        public void send(string from,string [] to,string [] cc,string title,string content)
        {
            MailMessage mailMsg = new MailMessage();
            mailMsg.From = new MailAddress(from);
            if (to.Length > 0)
            {
                foreach(string s in to)
                {
                    mailMsg.To.Add(s);
                }
            }
            if (cc.Length > 0)
            {
                foreach (string s in cc)
                {
                    mailMsg.CC.Add(s);
                }
            }
            mailMsg.Subject = title;
            mailMsg.Body = content;
            mailMsg.BodyEncoding = Encoding.UTF8;
            mailMsg.IsBodyHtml = false;
            mailMsg.Priority = MailPriority.High;
            SmtpClient smtp = new SmtpClient();
            smtp.Credentials = new NetworkCredential(username, password);
            smtp.Port = 25;
            smtp.Host = domain;
            smtp.EnableSsl = false;
            smtp.SendCompleted += new SendCompletedEventHandler(SendMailCompleted);
            try
            {
                smtp.SendAsync(mailMsg, mailMsg);
            }
            catch (SmtpException ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }
    }
}
然后直接调用该类的send()方法即可,
实例代码如下:
Mail mail = new Mail("发邮件的地址", "发邮件的密码", "邮件的smtp地址");
0 0
原创粉丝点击