AI智能
改变未来

C# 发送邮件的两种方法 支持25端口和465端口

C# 通用的异步发送邮件的两种方法 支持25端口和465端口

如果需要异步先定义一个委托

//定义一个委托
protected delegate void AsyncSendEmaildelegate(EmailModel model, Dictionary<string, string> para, string connStr, string hid, Guid sendid);

第一种 支持25端口不支持465端口
using System.Net.Mail
protected void AsyncSendEmail(EmailModel model, Dictionary<string, string> para, string connStr, string hid, Guid sendid)
{
// 支持25端口不支持465
var db = new DbHotelPmsContext(connStr, hid, “”, null);
string template = “FPemail”;
var sendrecord = db.ImsSendRecords.Where(m => m.ID == sendid).FirstOrDefault();
db.Entry(sendrecord).State = EntityState.Modified;
string strbody = “”;
var email_server = para[“emailsendserver”];//邮箱服务器地址
var email_port = para[“emailsendport”];//端口
var email_from = para[“emailsendusername”];//发送者邮箱
var email_pass = para[“emailsendpassword”];//密码
if (email_server.IsNullOrEmpty() || email_port.IsNullOrEmpty() || email_from.IsNullOrEmpty() || email_pass.IsNullOrEmpty())
{
sendrecord.State = 3;
sendrecord.StateMessage = “邮箱配置参数不正确,可能为空”;
db.SaveChanges();
return;
}
model.BodyPara.Add(“Remark”, model.Remark);
template = string.Format(@“Content\\Template{0}.htm”, template);
// 建立一个邮件实体
MailAddress from = new MailAddress(email_from, model.FromName, Encoding.UTF8);
MailAddress to = new MailAddress(model.ToAddress);
MailMessage message = new MailMessage(from, to);
strbody = ReplaceText(model.BodyPara, template);
message.IsBodyHtml = true;
message.BodyEncoding = Encoding.UTF8;
message.Priority = MailPriority.High;
message.Body = strbody; //邮件BODY内容
message.Subject = model.Subject;
SmtpClient smtp = new SmtpClient();
smtp.EnableSsl = true;
smtp.Host = email_server;
smtp.Port = int.Parse(email_port);
smtp.Credentials = new NetworkCredential(email_from, email_pass);
try
{
smtp.Send(message); //发送邮件
sendrecord.State = 1;
sendrecord.StateMessage = “OK”;
sendrecord.MessageBody = JsonHelper.SerializeObject(message);
db.SaveChanges();
return;
}
catch (System.Net.Mail.SmtpException ex)
{
sendrecord.State = 3;
sendrecord.StateMessage = ex.Message;
db.SaveChanges();
return;
}
}

第二种 支持465 SLL
using System.Web.Mail;
protected void AsyncSendEmail(EmailModel model, Dictionary<string, string> para, string connStr, string hid, Guid sendid)
{
var db = new DbHotelPmsContext(connStr, hid, “”, null);
string template = “FPemail”;
var sendrecord = db.ImsSendRecords.Where(m => m.ID == sendid).FirstOrDefault();
db.Entry(sendrecord).State = EntityState.Modified;
string strbody = “”;
var email_server = para[“emailsendserver”];
var email_port = para[“emailsendport”];
var email_from = para[“emailsendusername”];
var email_pass = para[“emailsendpassword”];
if (email_server.IsNullOrEmpty() || email_port.IsNullOrEmpty() || email_from.IsNullOrEmpty() || email_pass.IsNullOrEmpty())
{
sendrecord.State = 3;
sendrecord.StateMessage = “邮箱配置参数不正确,可能为空”;
db.SaveChanges();
return;
}
model.BodyPara.Add(“Remark”, model.Remark);
template = string.Format(@“Content\\Template{0}.htm”, template);
strbody = ReplaceText(model.BodyPara, template);
MailMessage mmsg = new MailMessage();
//邮件主题
mmsg.Subject = model.Subject;
mmsg.BodyFormat = MailFormat.Html;
//邮件正文
mmsg.Body = strbody;
//正文编码
mmsg.BodyEncoding = Encoding.UTF8;
//优先级
mmsg.Priority = MailPriority.Normal;
//发件者邮箱地址
mmsg.From = email_from;
//发件人地址;
//收件人收箱地址
string email_address = model.ToAddress;
//if (!string.IsNullOrWhiteSpace(email_address))
//{
// mmsg.To = “”;//收件人地址
//}
//else
//{
mmsg.To = email_address + “”;//收件人地址
//}
mmsg.Fields.Add(“http://schemas.microsoft.com/cdo/configuration/smtpauthenticate”, “1”);
//用户名
mmsg.Fields.Add(“http://schemas.microsoft.com/cdo/configuration/sendusername”, email_from);
//密码
mmsg.Fields.Add(“http://schemas.microsoft.com/cdo/configuration/sendpassword”, email_pass);
//端口
mmsg.Fields.Add(“http://schemas.microsoft.com/cdo/configuration/smtpserverport”, email_port);
//是否ssl
mmsg.Fields.Add(“http://schemas.microsoft.com/cdo/configuration/smtpusessl”, “true”);
//Smtp服务器
System.Web.Mail.SmtpMail.SmtpServer = email_server;
try
{
SmtpMail.Send(mmsg);
sendrecord.State = 1;
sendrecord.StateMessage = “OK”;
sendrecord.MessageBody = JsonHelper.SerializeObject(mmsg);
db.SaveChanges();
return;
}
catch (Exception ex)
{
sendrecord.State = 3;
sendrecord.StateMessage = ex.Message;
db.SaveChanges();
return;
}
}

异步发邮件的回调
protected static void EmailcallBackMethod(IAsyncResult ar)
{
AsyncSendEmaildelegate caller = ar.AsyncState as AsyncSendEmaildelegate;
caller.EndInvoke(ar);
}

通用的模板替换方法
private static string ReplaceText(Dictionary<string, string> para, string template)
{
string path = string.Empty;
path = AppDomain.CurrentDomain.BaseDirectory + template;
if (path == string.Empty)
{
return string.Empty;
}
StreamReader read = new StreamReader(path);
string str = string.Empty;
str = read.ReadToEnd();
if (para != null)
{
foreach (var item in para)
{
str = str.Replace(\”{~\” + item.Key + “~}”, item.Value);
}
}
read.Dispose();
return str;
}

调用实例-同步

//发送邮件
if (fpcache.email != “”)
{
Dictionary<string, string> dic = new Dictionary<string, string>();
dic.Add(“fppdf”, url);
dic.Add(“kprq”, invoiceentity.CDate.Value.ToString());
dic.Add(“fpdm”, invoiceentity.InvoiceCode);
dic.Add(“fphm”, invoiceentity.InvoiceNo);
dic.Add(“xfmc”, fpcache.xfmc);
dic.Add(“gfmc”, invoiceentity.TaxName);
dic.Add(“jshj”, fpcache.Amount);
dic.Add(“xfsj”, fpcache.xfsj);
dic.Add(“fpid”, fpcache.invoiceID.ToString());
dic.Add(“hid”, fpcache.hid);
var connstr = ConnStrHelper.GetConnStr(logininfo.DbServer, logininfo.DbName, logininfo.DbUser, logininfo.DbPwd, “Invoice”);
var _sysParaService = DependencyResolver.Current.GetService();//
var para = _sysParaService.GetEmailSendPara();//这里是去数据库查询邮箱发送参数
AsyncSendEmail(new EmailModel()
{XXXXXX
Subject = “【@@@@】XXXXXX”,
Remark = “ajsdhahdahdih”,
BodyPara = dic,
FromName = “发送人昵称”,
ToAddress = fpcache.email
}, para, connstr, fpcache.hid, fpcache.sendID);/
}

调用实例-异步
//发送邮件
var fppdf = itools.GetFp(new Common.InvoiceTools.GetFp.GetFpRequestModel() { fpdm = invoicethis.InvoiceCode, fphm = invoicethis.InvoiceNo, nsrsbh = gettoken.map.nsrsbh, pkey = gettoken.map.pkey });
Dictionary<string, string> dic = new Dictionary<string, string>();
dic.Add(“fppdf”, fppdf.@object.url);
dic.Add(“kprq”, invoicethis.CDate.Value.ToString());
dic.Add(“fpdm”, invoicethis.InvoiceCode);
dic.Add(“fphm”, invoicethis.InvoiceNo);
dic.Add(“xfmc”, gettoken.map.nsrmc);
dic.Add(“gfmc”, invoicethis.TaxName);
dic.Add(“jshj”, invoicedetails.Sum(m => m.Amount).Value.ToString());
dic.Add(“xfsj”, invoicethis.BsnsDate.ToString());
//下边参数查询用的
dic.Add(“fpid”, invoicethis.Id.ToString());
dic.Add(“hid”, hid);
var sendid = Guid.NewGuid();
//异步发送邮件
//先插入发送记录
var senddb = GetService();
var connstr = ConnStrHelper.GetConnStr(invlogin.DbServer, invlogin.DbName, invlogin.DbUser, invlogin.DbPwd, “Invoice”);
senddb.Add(new ImsSendRecord()
{
CDate = DateTime.Now,
HID = hid,
ID = sendid,
InvoiceID = invoicethis.Id,
State = 2,
SType = 1,
Target = email
});
senddb.Commit();
//异步发送邮件
var _sysParaService = DependencyResolver.Current.GetService();
var para = _sysParaService.GetEmailSendPara();
AsyncSendEmaildelegate asyncsendemail = new AsyncSendEmaildelegate(AsyncSendEmail);
IAsyncResult result = asyncsendemail.BeginInvoke(new EmailModel()
{
Subject = “XXXXX”,
Remark = “XXXXXXXX”,
BodyPara = dic,
FromName = “XXXXXX”,
ToAddress = email
}, para, connstr, hid, sendid, EmailcallBackMethod, asyncsendemail);
hb[“code”] = “1”;
hb[“msg”] = “已发送,请稍后查收”;
ResponseWrite(hb); return;

赞(0) 打赏
未经允许不得转载:爱站程序员基地 » C# 发送邮件的两种方法 支持25端口和465端口