C#使用SMTP发送邮件

需要用到的命名空间:

using System.Net.Mail;
using System.IO;
using System.Text.RegularExpressions;
using System.Collections;
using System.ComponentModel;

发送邮件的方法如下:

其中处理附件的代码实现的效果是自动根据文件扩展名获得ContentType值,且发送的附件名与上传的文件名一致。

/// <summary>
/// 发送邮件给相关人
/// </summary>
/// <param name="sendToList">收件人列表(以分号分隔)</param>
/// <param name="attachment">附件路劲(服务器端路劲)</param>
/// <param name="subject">邮件主题</param>
/// <param name="mailBody">邮件内容</param>
/// <param name="sysEmail">使用的系统邮箱</param>
/// <param name="sysEmailPwd">系统邮箱密码</param>
/// <param name="smtpUrl">系统邮箱SMTP的URL</param>
/// <returns>返回空字符串代表成功,否则为错误信息字符串</returns>
public string SendEmail(string sendToList, Hashtable attachment, string subject, string mailBody, 
                        string sysEmail, string sysEmailPwd, string smtpUrl)
{
    try
    {
        string strReturn = "";
        //return strReturn;

        MailMessage mail = new MailMessage();

        sendToList = sendToList.Trim().TrimEnd(';');
        if (sendToList.Length == 0)
        {
            return "收件人地址为空";
        }

        mail.From = new MailAddress(sysEmail);
        foreach (string to in sendToList.Split(';'))
        {
            if (Regex.IsMatch(to, @"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"))
            {
                mail.To.Add(to);
            }
            else
            {
                strReturn += string.Format("{0}邮箱格式错误,未发送\\n", to);
            }
        }

        if (strReturn == "")
        {
            //mail.IsBodyHtml = true;
            //mail.Body = mailBody.Replace("\n\r", "<br />");
            mail.IsBodyHtml = false;
            mail.Subject = subject;
            mail.Body = mailBody;
            mail.SubjectEncoding = Encoding.GetEncoding("UTF-8");
            mail.BodyEncoding = Encoding.GetEncoding("UTF-8");

            if (attachment.Count > 0)
            {
                //mail.Body = mailBody +"\n\r随邮件带附件:";
                string filePath;
                string fileOldName;
                //FileInfo fileInfo;

                foreach (System.Collections.DictionaryEntry objDE in attachment)
                {
                    filePath = objDE.Key.ToString();
                    fileOldName = objDE.Value.ToString();
                    if (File.Exists(filePath))
                    {
                        //fileInfo = new FileInfo(filePath);
                        //if (fileInfo.Length / 1024 >= 10240)//大于10MB
                        //{
                        //    mail.Body += "大附件:<a href='" + System.Web.HttpContext.Current.Request.Url.Host + "/UploadedFiles/" +
                        //                  filePath.Split(new string[] { "\\UploadedFiles\\" }, StringSplitOptions.None)[1] + "'>" + fileOldName + "</a>";
                        //    continue;
                        //}

                        System.Net.Mime.ContentType contentType = new System.Net.Mime.ContentType();
                        contentType.Name = fileOldName;
                        contentType.MediaType = GetContentTypeForFileName(filePath);
                        Attachment mailAttach = new Attachment(new FileStream(objDE.Key.ToString(), FileMode.Open, FileAccess.Read, FileShare.Read), contentType);
                        //Attachment mailAttach = new Attachment(objDE.Key.ToString());
                        mail.Attachments.Add(mailAttach);
                    }
                }
            }

            SmtpClient smtp = new SmtpClient(smtpUrl);
            smtp.Credentials = new System.Net.NetworkCredential(sysEmail, sysEmailPwd);

            //smtp.Port = 25;
            //smtp.Timeout = 180000;//3分钟,默认为100秒
            //smtp.EnableSsl = false;

            smtp.Send(mail);

            //smtp.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback);
            //smtp.SendAsync(mail, "异步发送邮件");

            mail.Dispose();
        }

        return strReturn;
    }
    catch (Exception ex)
    {
        logger.Error("【邮件发送】异常描述:\t" + ex.Message);
        logger.Error("【邮件发送】异常方法:\t" + ex.TargetSite);
        logger.Error("【邮件发送】异常堆栈:\t" + ex.StackTrace);
    }
}

获取文件ContentType值的方法:

/// <summary>
/// 获取文件ContentType值
/// </summary>
/// <param name="fileName">文件完整路劲</param>
/// <returns>文件ContentType值</returns>
private string GetContentTypeForFileName(string fileName)
{
    string ext = System.IO.Path.GetExtension(fileName);
    using (Microsoft.Win32.RegistryKey registryKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext))
    {
        if (registryKey == null)
            return null;
        string value = registryKey.GetValue("Content Type").ToString();
        return (value == null) ? string.Empty : value;
    }
}

 

 

posted @ 2013-08-19 16:50  志在必得Shaun  阅读(1137)  评论(0编辑  收藏  举报