Mailkit 发送附件邮件
Mailkit 发送附件邮件
写在开头
恰好最近的项目有个业务需求,需要发送含多个附件的邮件,所以以此文记录
项目需引入
Mailkit
库。
基础代码
var message = new MimeMessage();
message.From.Add (new MailboxAddress ("发出人", "邮箱"));
message.To.Add (new MailboxAddress ("发送人", "邮箱"));
message.Cc.Add (new MailboxAddress ("抄送人", "邮箱"));
message.Subject = "标题";
builder.TextBody = @"文本";
builder.HtmlBody ="<span>html字符串</span>";
await builder.Attachments.AddAsync ("文件名.xlsx", stream流);//附件
message.Body = builder.ToMessageBody ();
using var client = new SmtpClient();
await client.ConnectAsync("smtp.exmail.qq.com", 25, false);//填对应的
await client.AuthenticateAsync("邮箱名", "密码");
await client.SendAsync(message);
await client.DisconnectAsync(true);
附件处理
首先通过Dictionary
存储相关数据:
var dic=new Dictionary<string,MemoryStream>();
var data1=list1.Select(a=>new{字段名1=值1,字段名2=值2});
Output(data1,"表名1",ref dic);
var data2=list2.Select(a=>new{字段名1=值1,字段名2=值2});
Output(data2,"表名2",ref dic);
.......
//附件
foreach (var keyval in dic)
{
await builder.Attachments.AddAsync (keyval.Key, keyval.Value);
}
每一个表都要
select new
一次,这也太麻烦了,有什么更好的解决方案呢?
是的,我们可以使用特性及反射进一步处理简化代码。
[Description("表名")]
public class Table1{
[Description("数字编号")]
public int Num{get;set;}
[Description("名称")]
public string Name{get;set;}
}
var sheetDes=typeof(T).GetCustomAttribute<DescriptionAttribute>()?.Description;
//var sheetDes=typeof(T).GetCustomAttribute(typeof(DescriptionAttribute)) as DescriptionAttribute;
foreach (var prop in typeof(T).GetProperties())
{
var val = prop.GetCustomAttribute<DescriptionAttribute>()?.Description;
}
写在最后
ok,到这也差不多了,可以发现,反射
、泛型
、特性
等C#基础特性可以很好的帮助我们更快的完成业务需求开发!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)