吟空麦子

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

麦子在此分享一个c#发送邮件的实例代码,代码是麦子亲自写出来,而且也亲测过,可以正常发送邮件。

为了方便使用,麦子把发邮件的核心代码提取为一个类(Mail),

代码如下:

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()方法即可,

实例代码如下:

//3个字符串分别填STMP用户名,STMP密码和SMTP地址
Mail mail = new Mail("admin@ykmaiz.com", "***", "smtp.ykmaiz.com");

mail.send("发邮件的地址", new string[] { "收件人地址" }, new string[] { "抄送人地址" }, "邮件标题", "邮件内容");

很方便,赶快去试试吧!

码字很辛苦,转载请注明来自吟空麦子的技术博客《C#发送邮件的方法及实例代码》 原文链接:https://www.ykmaiz.com/csharp/125.html

评论