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#基础特性可以很好的帮助我们更快的完成业务需求开发!