C#发送邮件

邮件帮组类

using System; 
using System.Collections.Generic; 
using System.IO; 
using System.Net; 
using System.Net.Mail; 
using System.Net.Mime; 
using System.Text; 
using System.Threading; 
using System.Threading.Tasks; 

namespace LionTech.Utility.MELMRP 
{ 
public class MailSender 
{ 
private String _EmailSMTPServer = String.Empty; //SMTP位置 
private int _EmailSMTPPort = 25; //SMTP Port 
private mailAddr _sender = new mailAddr("", ""); 
private String _Subject = String.Empty;//信件標題 
private String _Content = String.Empty;//信件內容 
private List<mailAddr> _ReplayTo = new List<mailAddr>();//信件回覆位置 
private List<mailAddr> _Receiver = new List<mailAddr>();//信件接收者 
private List<mailAddr> _CC = new List<mailAddr>();//副本 
private List<mailAddr> _BCC = new List<mailAddr>();//密件副本 
private Boolean _EnableSSL = false;//是否啟用SSL 
private Boolean _EnableTHML = true;//是否為HTML內容 
private Boolean _Notification = false;//信件回函 
private List<AttachmentFile> _AttachmentFiles = new List<AttachmentFile>();//附件 
private Encoding _SubjectEncoding = Encoding.UTF8;//標題編碼 
private Encoding _ContentEncoding = Encoding.UTF8;//內容編碼 
private MailPriority _Priority = MailPriority.Normal;//優先順序 

/// <summary> 設定、取得信件寄件者 </summary> 
public mailAddr sender { get { return _sender; } set { _sender = value; } } 
/// <summary> 設定、取得信件標題 </summary> 
public String Subject 
{ 
get { return _Subject; } 
set 
{ 
//_Subject = value; 
_Subject = String.Format("=?UTF-8?B?{0}?=", Convert.ToBase64String(Encoding.UTF8.GetBytes(value))); 
} 
} 
/// <summary> 設定、取得信件內容 </summary> 
public String Content { get { return _Content; } set { _Content = value; } } 
/// <summary> 設定、取得信件回覆位置 </summary> 
public List<mailAddr> ReplayTo { get { return _ReplayTo; } set { _ReplayTo = value; } } 
/// <summary> 設定、取得信件接收者 </summary> 
public List<mailAddr> Receiver { get { return _Receiver; } set { _Receiver = value; } } 
/// <summary> 設定、取得信件副本 </summary> 
public List<mailAddr> CC { get { return _CC; } set { _CC = value; } } 
/// <summary> 設定、取得信件密件副本 </summary> 
public List<mailAddr> BCC { get { return _BCC; } set { _BCC = value; } } 
/// <summary> 設定、取得是否啟用SSL(def:false) </summary> 
public bool EnableSSL { get { return _EnableSSL; } set { _EnableSSL = value; } } 
/// <summary> 設定、取得是否為HTML內容(def:true) </summary> 
public bool EnableTHML { get { return _EnableTHML; } set { _EnableTHML = value; } } 
/// <summary> 設定、取得是否需要信件回函(def:false) </summary> 
public bool Notification { get { return _Notification; } set { _Notification = value; } } 
/// <summary> 設定、取得信件附件 </summary> 
public List<AttachmentFile> AttachmentFiles { get { return _AttachmentFiles; } set { _AttachmentFiles = value; } } 
/// <summary> 設定、取得信件標題編碼 </summary> 
public Encoding Encoding_Subject { get { return _SubjectEncoding; } set { _SubjectEncoding = value; } } 
/// <summary> 設定、取得信件內容編碼 </summary> 
public Encoding Encoding_Content { get { return _ContentEncoding; } set { _ContentEncoding = value; } } 
/// <summary> 設定、取得信件優先順序 </summary> 
public MailPriority Priority { get { return _Priority; } set { _Priority = value; } } 


/// <summary> 設定、取得發送郵件的 thread *非同步發信新增 </summary> 
public Thread SendThread { get; set; } 

/// <summary> 建構子 </summary> 
/// <param name="SMTPServer">SMTP位置</param> 
/// <param name="SMTPPort">SMTP Port (通常為 25)</param> 
public MailSender(String SMTPServer, int SMTPPort) 
{ 
_EmailSMTPServer = SMTPServer; 
_EmailSMTPPort = SMTPPort; 
} 
/// <summary> 建構子 (default port:25) </summary> 
/// <param name="SMTPServer"></param> 
public MailSender(String SMTPServer) : this(SMTPServer, 25) { } 
public MailSender() { } 


#region 非同步發信新增的程式區段 ---------------------------------------------- 
/// <summary> 非同步發信函數。</summary> 
public void BeginSend() 
{ 
SendThread = new Thread(new ThreadStart(BeginSendSubThread)); 
SendThread.Name = "MailSendThread"; 
SendThread.Start(); 
} 
private void BeginSendSubThread() 
{ 
try { Send(); } 
catch { } 
SendThread.Abort(); //結束非同步發信的執行緒 
} 
#endregion -------------------------------------------------------------------- 

/// <summary>信件發送函數。</summary> 
public bool Send() 
{ 
MailMessage mail = new MailMessage(); 
mail.From = new MailAddress(sender.mail, sender.name);//寄件者 
mail.IsBodyHtml = EnableTHML; //信件本文是否為HTML 
mail.Body = Content; //設定本文內容 
mail.BodyEncoding = _ContentEncoding; 
mail.Subject = Subject; //設定信件標題 
mail.SubjectEncoding = _ContentEncoding; 
//mail.Priority = MailPriority.High; 

if (Receiver.Count > 0)//收件者 
Parallel.ForEach(Receiver, (item, loopState) => { if (IsValidEmail(item.mail)) mail.To.Add(new MailAddress(item.mail, item.name)); }); 

if (ReplayTo.Count > 0)//設定信件回覆位置 
Parallel.ForEach(ReplayTo, (item, loopState) => { if (IsValidEmail(item.mail)) mail.ReplyToList.Add(new MailAddress(item.mail, item.name)); }); 

if (CC.Count > 0)//加入信件副本 
Parallel.ForEach(CC, (item, loopState) => { if (IsValidEmail(item.mail)) mail.CC.Add(new MailAddress(item.mail, item.name)); }); 

if (BCC.Count > 0)//加入信件密件副本 
Parallel.ForEach(BCC, (item, loopState) => { if (IsValidEmail(item.mail)) mail.Bcc.Add(new MailAddress(item.mail, item.name)); }); 

if (Notification && IsValidEmail(sender.mail))//回條 
mail.Headers.Add("Disposition-Notification-To", sender.mail); 

if (AttachmentFiles.Count > 0) 
{ 
Parallel.ForEach(AttachmentFiles, (item, loopState) => 
{ 
if (item != null && item.FileStream != null && item.FileStream.Length > 0 && !String.IsNullOrWhiteSpace(item.FileName)) 
mail.Attachments.Add(new Attachment(item.FileStream, item.FileName)); 
}); 
} 

mail.Priority = _Priority;//優先順序 

try 
{ 
//如果是空的,取 webconfig 中設定值 
if (string.IsNullOrWhiteSpace(_EmailSMTPServer)) 
{ 
using (SmtpClient SC = new SmtpClient()) 
{ 
SC.Send(mail); 
} 
} 
else 
{ 
SmtpClient SC = new SmtpClient(_EmailSMTPServer, _EmailSMTPPort); 
SC.EnableSsl = EnableSSL; //是否開啟SSL 
SC.Host = _EmailSMTPServer; 
SC.Port = _EmailSMTPPort; 
SC.UseDefaultCredentials = true; 
//设置邮箱发送服务 
SC.Credentials = new NetworkCredential("3781100649@163.com", "13055673352zzz"); 
SC.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network; 
SC.Send(mail); //發送 
return true; 
} 
} 
catch (Exception ex) 
{ 
return false; 
} 
return false; 
} 


public static bool IsValidEmail(string strIn) 
{ 
if (!String.IsNullOrWhiteSpace(strIn)) 
{ 
// Return true if strIn is in valid e-mail format. 
return System.Text.RegularExpressions.Regex.IsMatch(strIn, 
@"^(?("")("".+?""@)|(([0-9a-zA-Z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-zA-Z])@))" + 
@"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,6}))$"); 
} 
else 
return false; 
} 
} 

public class mailAddr 
{ 
private String _name = String.Empty; 
private String _mail = String.Empty; 
private String _encodeName = string.Empty; 
public String name { get { return _name; } } 
public String mail { get { return _mail; } } 
public String encodeName { get { return _encodeName; } } 

public mailAddr(String name, String email) { _name = name; _mail = email; _encodeName = !string.IsNullOrWhiteSpace(name) ? String.Format("=?UTF-8?Q?{0}?=", Uri.EscapeDataString(name).Replace("%", "=")) : ""; } 
} 

public class AttachmentFile 
{ 
private Stream _fStream; 
private String _fName = String.Empty; 

public Stream FileStream { get { return _fStream; } } 
public String FileName { get { return _fName; } } 

public AttachmentFile(Stream FileStream, String FileName) { _fStream = FileStream; _fName = FileName; } 
} 
} 
View Code

发送邮件

//获取文件流
                 FileStream fileStream = new FileStream(strFilePath, FileMode.Open, FileAccess.Read, FileShare.Read);
                 //获取文件名
                 string FileName = "Web.config";
                 byte[] bytes = new byte[fileStream.Length];
                 fileStream.Read(bytes, 0, bytes.Length);
                 Stream stream = new MemoryStream(bytes);
                 stream.Flush();
                 fileStream.Close();
                 //设置邮件信息
                 MailSender sendEmail = new MailSender("smtp.163.com", 25)
                 {
                     //发件人
                     sender = new mailAddr("发送人名称", "邮箱地址"),
                     //收件人
                     Receiver = new List<mailAddr>() { new mailAddr("张伟东", Buffer_Addresseeemail) },
                     //主旨
                     Subject = Query_title,
                     //内容
                     Content = Query_content,
                     //发送附件
                     AttachmentFiles = new List<AttachmentFile>() { new AttachmentFile(stream, FileName) }
                 };
                 //发送邮件
                 if (sendEmail.Send())
                 {
                     //发送邮件成功!
                     stream.Close();
                     return true;
                 }
                 else
                 {
                     //发送邮件失败!
                     stream.Close();
                     return false;
                 }

进一步操作,封装邮件发送方法,可通过网络发送和发送到本地硬盘中

        #region 發送Email到本地
        /// <summary>
        /// 發送Email到本地
        /// </summary>
        /// <param name="senderEmail">發送者Email地址</param>
        /// <param name="toEmail">接收者Email地址</param>
        /// <param name="subject">標題</param>
        /// <param name="content">內容</param>
        /// <param name="locationPath">本地存放絕對路徑</param>
        public void sendEmailToLocation(string senderEmail, List<mailAddr> toEmail, string subject, string content, string locationPath)
        {
            MailMessage email = new MailMessage();
            email.From = new MailAddress(senderEmail);
            foreach (mailAddr addr in toEmail)
            {
                if (string.IsNullOrWhiteSpace(addr.mail)) continue;
                email.To.Add(new MailAddress(addr.mail));
            }
            email.IsBodyHtml = true;
            email.Body = content;
            email.Subject = subject;
            SmtpClient stmp = new SmtpClient(Account.EmailSmtp, Account.EmailSmtpPort);
            stmp.UseDefaultCredentials = true;
            stmp.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory;
       //发送的路径 stmp.PickupDirectoryLocation
= locationPath; stmp.Send(email); } #endregion #region 發送網絡郵件 /// <summary> /// 發送網絡郵件 /// </summary> /// <param name="senderName">發送者發送郵件名稱</param> /// <param name="senderEmail">發送者郵箱地址</param> /// <param name="toEmail">接受者</param> /// <param name="subject">主題</param> /// <param name="content">內容</param> public void sendEmailToNetWork(string senderName, string senderEmail, List<mailAddr> toEmail, string subject, string content) { //邮件发送类 MailSender sendEmail = new MailSender(Account.EmailSmtp, Account.EmailSmtpPort); //发送者 sendEmail.sender = new mailAddr(senderName, Account.mailSenderMail); //接收者 foreach (mailAddr addr in toEmail) { if (string.IsNullOrWhiteSpace(addr.mail)) continue; sendEmail.Receiver.Add(new mailAddr(addr.name, addr.mail)); } //主题 sendEmail.Subject = subject; //内容 sendEmail.Content = content; sendEmail.EnableTHML = true; //发送邮件 sendEmail.BeginSend(); } #endregion

详细解释

public static void sendmail_2()
{
SmtpClient smtp = new SmtpClient(); //实例化一个SmtpClient
smtp.DeliveryMethod = SmtpDeliveryMethod.Network; //将smtp的出站方式设为 Network
smtp.EnableSsl = false;//smtp服务器是否启用SSL加密
smtp.Host = "smtp.163.com"; //指定 smtp 服务器地址
smtp.Port = 25; //指定 smtp 服务器的端口,默认是25,如果采用默认端口,可省去
//如果你的SMTP服务器不需要身份认证,则使用下面的方式,不过,目前基本没有不需要认证的了
smtp.UseDefaultCredentials = true; //如果需要认证,则用下面的方式
smtp.Credentials = new NetworkCredential("a@163.com", "****");
MailMessage mm = new MailMessage(); //实例化一个邮件类
mm.Priority = MailPriority.High; //邮件的优先级,分为 Low, Normal, High,通常用 Normal即可
mm.From = new MailAddress("b@163.com", "真有意思测试", Encoding.GetEncoding(936));
//收件方看到的邮件来源;
//第一个参数是发信人邮件地址
//第二参数是发信人显示的名称
//第三个参数是 第二个参数所使用的编码,如果指定不正确,则对方收到后显示乱码 
//936是简体中文的codepage值
//注:上面的邮件来源,一定要和你登录邮箱的帐号一致,否则会认证失败
mm.ReplyTo = new MailAddress("b@163.com", "我的接收邮箱", Encoding.GetEncoding(936));
//ReplyTo 表示对方回复邮件时默认的接收地址,即:你用一个邮箱发信,但却用另一个来收信
//上面后两个参数的意义, 同 From 的意义
//mm.CC.Add("a@163.com,b@163.com,c@163.com");
//邮件的抄送者,支持群发,多个邮件地址之间用 半角逗号 分开
//当然也可以用全地址,如下:
mm.CC.Add(new MailAddress("c@163.com", "抄送者A", Encoding.GetEncoding(936)));
//mm.CC.Add(new MailAddress("b@163.com", "抄送者B", Encoding.GetEncoding(936)));
//mm.CC.Add(new MailAddress("c@163.com", "抄送者C", Encoding.GetEncoding(936)));
//mm.Bcc.Add("d@163.com,e@163.com");
//邮件的密送者,支持群发,多个邮件地址之间用 半角逗号 分开
//当然也可以用全地址,如下:
//mm.CC.Add(new MailAddress("d@163.com", "密送者D", Encoding.GetEncoding(936)));
//mm.CC.Add(new MailAddress("e@163.com", "密送者E", Encoding.GetEncoding(936)));
//mm.Sender = new MailAddress("xxx@xxx.com", "邮件发送者", Encoding.GetEncoding(936));
//可以任意设置,此信息包含在邮件头中,但并不会验证有效性,也不会显示给收件人
//说实话,我不知道有啥实际作用,大家可不理会,也可不写此项
//mm.To.Add("g@163.com,h@163.com");
//邮件的接收者,支持群发,多个地址之间用 半角逗号 分开
//当然也可以用全地址添加
mm.To.Add(new MailAddress("g@163.com", "接收者g", Encoding.GetEncoding(936)));
//mm.To.Add(new MailAddress("h@163.com", "接收者h", Encoding.GetEncoding(936)));
mm.Subject = "这是邮件标题-测试"; //邮件标题
mm.SubjectEncoding = Encoding.GetEncoding(936); // 这里非常重要,如果你的邮件标题包含中文,这里一定要指定,否则对方收到的极有可能是乱码。
// 936是简体中文的pagecode,如果是英文标题,这句可以忽略不用
mm.IsBodyHtml = true; //邮件正文是否是HTML格式
mm.BodyEncoding = Encoding.GetEncoding(936); //邮件正文的编码, 设置不正确, 接收者会收到乱码
mm.Body = "<font color=\"red\">邮件测试,呵呵</font>"; //邮件正文
mm.Attachments.Add(new Attachment(@"c:\d\1.doc", System.Net.Mime.MediaTypeNames.Application.Rtf)); //添加附件,第二个参数,表示附件的文件类型,可以不用指定
//可以添加多个附件
//mm.Attachments.Add(new Attachment(@"d:b.doc"));
smtp.Send(mm); //发送邮件,如果不返回异常, 则大功告成了。
}

 

 

 

posted @ 2016-01-29 16:00  可可味  阅读(296)  评论(0编辑  收藏  举报