LimFx的EmailService使用说明

环境设置见如何使用和https://limfx.pro相同的后端技术?

说明

LimFx的EmailService功能在注入后会自动多线程帮助您发送队列中的邮件,允许您使用razor文件作为email模板。
此功能需要使用mongodb存储Email信息


注入、设置

首先,我们使用的Email需要一个c#类来存储,这个类需要继承一个类,两个接口:Entity/IEmail/ISearchable
本教程使用的类如下:

public class SampleEmail : Entity, IEmail, ISearchAble
{
    //发送者名称
    public string Sender { get; set; }
    //希望发送的时间
    public DateTime ExpectSendTime { get; set; }
    //接收者的email集合
    public List<string> Receivers { get; set; }
    //标题
    public string Subject { get;set; }
    //razor模板的路径
    public string RazorTemplate { get; set; }
    //用来做字符串搜索的,不需要此功能的可以无视该属性
    public string SearchAbleString { get; set; }
}

依赖注入:

services.AddEmailSenderService<SampleEmail>(op =>
{
    //mongodb数据库名称
    op.DataBaseName = "LimFxSample";
    //连接字符串
    op.ConnectionString = "mongodb://localhost:27017";
    //集合名称
    op.EmailCollectionName = "email";
    //每两次数据库检查之间的时间间隔,单位毫秒
    op.Interval = 5000;
    //最大允许线程数
    op.MaxEmailThreads = 5;
    //发送者默认名称
    op.SenderName = "Sample";
    //smtp服务器
    op.SmtpHost = "sample@sample.xyz";
    //密码
    op.SmtpPassword = "samplepassword";
    //账号
    op.SmtpSender = "sampleaccount";
    //默认razor模板地址
    op.TemplateDir = "sample.cshtml";
});

本服务使用ssl,端口使用465
依赖注入方法有两个重载,这里只介绍一种。另一种使用appsetting.json文件进行配置

发送Email

[Route("[controller]")]
[ApiController]
public class EmailController : ControllerBase
{
    EmailSender<SampleEmail> emailSender;
    public EmailController(EmailSender<SampleEmail> emailSender)
    {
        this.emailSender = emailSender;
    }
    [HttpPost("send")]
    public async ValueTask SendEmailAsync()
    {
        var e = new SampleEmail()
        {
            ExpectSendTime = DateTime.UtcNow,
            Receivers = new List<string>(),
        };
        e.Receivers.Add("sample@sample.com");
        await emailSender.QueueEmailAsync(e);
    }
}

是不是很简单?
喜欢的话点个赞吧~


本文章使用limfx的vsocde插件快速发布