使用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:

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);
}
}
}
发送成功:

参考文献
https://www.shuzhiduo.com/A/nAJv4neadr/
https://learn.microsoft.com/zh-cn/dotnet/api/system.net.mail.smtpclient?redirectedfrom=MSDN&view=net-6.0

浙公网安备 33010602011771号