使用System.Net.Mail中的SMTP发送邮件

使用简单邮件传输协议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:

 

 

 

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
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);
        }
    }
}<br><br> 

   发送成功

 

 

1
参考文献 <br>https://www.shuzhiduo.com/A/nAJv4neadr/<br>https://learn.microsoft.com/zh-cn/dotnet/api/system.net.mail.smtpclient?redirectedfrom=MSDN&view=net-6.0
posted @   VinceLi  阅读(365)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
点击右上角即可分享
微信分享提示