使用简单邮件传输协议SMTP异步发送邮件

想要实现SMTP发送邮件,你需要了解这些类

SmtpClient :使用配置文件设置来初始化 SmtpClient类的新实例。

它包含以下属性:

Host:设置用于SMTP服务的主机名或主机IP;

Port:设置用于SMTP服务的端口(一般设置为25);

Credentials:身份验证;

Send:直接发送邮件;

SendAsync:异步发送邮件(不阻止调用线程)

MailMessage:表示一封电子邮件。

它包含以下属性:

Attachment:表示文件附件;

CC:抄送;

Subject:主题;

From:发件人

Priority:优先级;

Body:正文;

BodyEncoding:Content-type。

此外  SmtpClient类不具有Finalize方法,因此应用程序必须调用Dispose以显式释放资源。

UI:

 

 

 

 

 

using System.Configuration;
using System.Web.Mvc;
using pis.Data.Dto;
using pis.Service;
using System.IO;
using System.Text;
using System.Net.Mail;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;
using System.Net.Mime;

namespace pis.Web.Areas.Business.Controllers
{
    public class OqcOrderController : BaseController
    {
        

        public string SendMail(string Subject,string SendTo,string CopyTo,string Context)
        {
            var result = new ResultTemplate() { ErrorCode = -1, Message = "发送失败!" };
            try
            {
                string MailServer = ConfigurationManager.AppSettings["MailHost"]?.ToString().Trim(); //Config.GetAppValue("MailHost");
                //用户名
                string MailUserName = ConfigurationManager.AppSettings["MailUserName"]?.ToString().Trim(); //Config.GetAppValue("MailUserName");
                // 密码
                string MailPassword = ConfigurationManager.AppSettings["MailPassword"]?.ToString().Trim(); //Config.GetAppValue("MailPassword");
                // 名称
                string MailName = ConfigurationManager.AppSettings["MailName"]?.ToString().Trim();

                SmtpClient smtpclient = new SmtpClient(MailServer, 25);
                //构建发件人的身份凭据类
                smtpclient.Credentials = new NetworkCredential(MailUserName, MailPassword);
                //SSL连接
                smtpclient.EnableSsl = false;
                //构建消息类
                MailMessage objMailMessage = new MailMessage();
                //设置优先级
                objMailMessage.Priority = MailPriority.High;
                
                //消息发送人
                objMailMessage.From = new MailAddress(MailUserName, MailName, Encoding.UTF8);
                //标题
                objMailMessage.Subject = Subject.Trim();
                objMailMessage.To.Add(SendTo);
                objMailMessage.CC.Add(CopyTo);
                //标题字符编码
                objMailMessage.SubjectEncoding = Encoding.UTF8;
                //正文
                //body = body.Replace("\r\n", "<br>");
                //body = body.Replace(@"\r\n", "<br>");
                objMailMessage.Body = Context.Trim();
                objMailMessage.IsBodyHtml = true;
                //内容字符编码
                objMailMessage.BodyEncoding = Encoding.UTF8;
                //添加附件
                string fileName = @"D:\WebRoot\PIS Web\PIS_Normal\OQCFiles\15 Pack换型时长分析Weekly.xlsx";
                //fileName = @"E:\Temp\CS22030042_KCP1.pdf";
                Attachment attach = new Attachment(fileName);//将文件路径付给Attachment的实例化对象
                ContentDisposition dispo = attach.ContentDisposition;//获取信息并读写附件
                dispo.CreationDate = FileHelper.GetCreationTime(fileName);
                dispo.ModificationDate = FileHelper.GetLastWriteTime(fileName);
                dispo.ReadDate = FileHelper.GetLastAccessTime(fileName);
                objMailMessage.Attachments.Add(attach);//将附件加入邮件中

                ServicePointManager.ServerCertificateValidationCallback = delegate (Object obj, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { return true; };
                //发送
                smtpclient.Send(objMailMessage);
                result.ErrorCode = 0;
                result.Message = "发送成功";
                
            }
            catch(Exception ex)
            {
                result.Message += ex.Message;
            }
            return ResultHelper.ToJsonResult(result);
        }
        /// <summary>
        /// 上传附件
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string UploadFile()
        {
            var result = new ResultTemplate() { ErrorCode = 1, Message = "上传失败!", Data = null };
            try
            {
                var category = Request["category"];
                string root = string.Empty;
                if (!string.IsNullOrEmpty(category))
                {
                    root = Path.Combine(FileServerConfig.FileRootPath, category);
                }
                else { root = FileServerConfig.FileRootPath; }
                if (!Directory.Exists(root))
                {
                    Directory.CreateDirectory(root);
                }
                var files = FileHelper.GetFileControls();
                string Sql = string.Empty;

                if (files.Count == 0)
                {
                    result.Message = "上传文件列表为空";
                    return ResultHelper.ToJsonResult(result);
                }
                if (files.Count > 0)
                {
                    var file = files[files.Count - 1];
                    var stream = file.InputStream;
                    var fileBinary = new byte[stream.Length];
                    stream.Read(fileBinary, 0, fileBinary.Length);
                    var directory = Path.Combine(root, DateTime.Now.ToString("yyyyMM"));
                    if (!Directory.Exists(directory))
                    {
                        Directory.CreateDirectory(directory);
                    }
                    string extension = Path.GetExtension(file.FileName);
                    var filename = string.Format("{0}{1}", Guid.NewGuid().ToString(), extension);
                    var path = Path.Combine(directory, file.FileName);
                    FileHelper.CreateFile(path, fileBinary);
                    string relativePath = root + "/" + DateTime.Now.ToString("yyyyMM") + "/" + file.FileName;
                    //var projImage = new ProjectImages() { BillNo = billNo, ImagePath = relativePath, FileName = file.FileName };
                    //Sql = $@"if exists(select 1 from ProjectImages where BillNo=@BillNo) begin Update ProjectImages SET ImagePath=@ImagePath,FileName=@FileName,UpdateDate=getdate() where BillNo=@BillNo; end 
                    //      else begin Insert into ProjectImages(Id,BillNo,ImagePath,FileName,UpdateDate) values(newid(),@BillNo,@ImagePath,@FileName,getdate()); end";
                    //int effectRows = SqlHelper.Execute(Sql, projImage);
                    //if (effectRows > 0)
                    //{
                    result.ErrorCode = 0;
                    result.Message = file.FileName;
                    result.Token = relativePath;
                    //}
                }
            }
            catch (Exception ex)
            {
                result.Message += ex.Message;
            }
            return ResultHelper.ToJsonResult(result);
        }
    }
}

 发送成功:

 

 

原文地址:http://www.cnblogs.com/ldc218/p/16814110.html

1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长! 2. 分享目的仅供大家学习和交流,请务用于商业用途! 3. 如果你也有好源码或者教程,可以到用户中心发布,分享有积分奖励和额外收入! 4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解! 5. 如有链接无法下载、失效或广告,请联系管理员处理! 6. 本站资源售价只是赞助,收取费用仅维持本站的日常运营所需! 7. 如遇到加密压缩包,默认解压密码为"gltf",如遇到无法解压的请联系管理员! 8. 因为资源和程序源码均为可复制品,所以不支持任何理由的退款兑现,请斟酌后支付下载 声明:如果标题没有注明"已测试"或者"测试可用"等字样的资源源码均未经过站长测试.特别注意没有标注的源码不保证任何可用性