.NET 个人博客-发送邮件优化?

这篇具有很好参考价值的文章主要介绍了.NET 个人博客-发送邮件优化?。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

个人博客-发送邮件优化🧐

前言

之前的发送邮件就弄了个方法,比如回复评论会给评论的人发送邮件,留言回复也是,而且2者的代码有很多一样的地方,比较冗余。然后也是抽空优化一下,思路也是比较常用的工厂+策略模式,然后评论回复和留言回复的模板是不一样的,所以需要创建模板类和方法。。。

内容比较多,可以自己创建个小项目试试~

模板创建

⌨先把模板给定义好

定义EmailContent

主要是用传入发送邮件的内容,Content参数为必须,其他的可以根据自己的需求进行更改。

public class EmailContent
{
    public string Content { get; set; }
    public string? Link { get; set; }
}

public class EmailContent<T>
{
    public string Content { get; set; }
    public string Link { get; set; }
    public T Data { get; set; }
}

首先创建一个基类定义邮件内容生成的方法:

  • EmailTemplate:基本模板类
  • SEmailTemplate:泛型模板类
public abstract class EmailTemplateBase
{
    protected abstract string GetStyle();
}

public abstract class EmailTemplate:EmailTemplateBase
{
    public string GenerateContent(EmailContent emailContent)
    {
        return $"<html>\n<head>\n<style>{GetStyle()}</style>\n</head>\n<body>\n{GetBodyContent(emailContent)}\n</body>\n</html>";
    }
    protected abstract string GetBodyContent(EmailContent emailContent);
}

public abstract class SEmailTemplate<T>:EmailTemplateBase
{
    public string GenerateContent(EmailContent<T> emailContent)
    {
        return $"<html>\n<head>\n{GetStyle()}\n</head>\n<body>\n{GetBodyContent(emailContent)}\n</body>\n</html>";
    }
    
    protected abstract string GetBodyContent(EmailContent<T> emailContent);
}

然后为每一种邮件内容创建一个子类:

情况一:简单情况

只发送简单的邮件内容,不包含对象等复杂内容。

  • GetStyle 里面写样式就行
  • GetBodyContent 里面写内容
public class MessageBoardNotificationEmailTemplate:EmailTemplate
{
    protected override string GetStyle()
    {
        return @"
            /* 添加样式 */
            body {
                font-family: Arial, sans-serif;
                font-size: 14px;
                line-height: 1.5;
                color: #333;
            }
            .box {
                background-color:#90F8FF ;
                border-radius: 5px;
                padding: 20px;
            }
            h1 {
                font-size: 24px;
                font-weight: bold;
                margin-bottom: 20px;
                color: #333;
            }
            p {
                margin-bottom: 10px;
                color: #333;
            }
            a {
                color: #333;
            }";
    }

    protected override string GetBodyContent(EmailContent emailContent)
    {
        return $@"
            <div class='box'>
                <h1>ZY知识库</h1>
                <h3>留言板通知</h3>
                <p>内容如下:{emailContent.Content}</p>
                <p>点击跳转:<a href='https://pljzy.top/MsgBoard?page=1'>留言板地址</a></p>
            </div>";
    }
}

情况二:复杂情况

  • GetStyle 同上
  • GetBodyContent 里面参数为泛型参数EmailContent<LinkExchange>,这样在发送邮件时就能发送对象信息
public class LinksNotificationEmailTemplate:SEmailTemplate<LinkExchange>
{
    protected override string GetStyle()
    {
        return "";
    }

    protected override string GetBodyContent(EmailContent<LinkExchange> emailContent)
    {
        const string blogLink = "<a href=\"https://pljzy.top\">ZY知识库</a>";
        var sb = new StringBuilder();
        sb.AppendLine($"<p>{emailContent.Content}</p>");
        sb.AppendLine($"<br>");
        sb.AppendLine($"<p>以下是您申请的友链信息:</p>");
        sb.AppendLine($"<p>网站名称:{emailContent.Data.Name}</p>");
        sb.AppendLine($"<p>介绍:{emailContent.Data.Description}</p>");
        sb.AppendLine($"<p>网址:{emailContent.Data.Url}</p>");
        sb.AppendLine($"<p>站长:{emailContent.Data.WebMaster}</p>");
        sb.AppendLine($"<p>补充信息:{emailContent.Data.Reason}</p>");
        sb.AppendLine($"<br>");
        sb.AppendLine($"<br>");
        sb.AppendLine($"<br>");
        sb.AppendLine($"<p>本消息由 {blogLink} 自动发送,无需回复。</p>");
        return sb.ToString();
    }
}

发送邮件服务

首先,创建一个接口定义邮件发送服务

public interface IEmailService
{
    Task SendEmail(string recipient, EmailTemplate template, EmailContent emailContent);
    Task SendEmail<T>(string recipient, SEmailTemplate<T> template,  EmailContent<T> emailContent);
}

然后创建实现类MimeKitEmailService ,这里用的是​MimeKit库生成邮件内容

public class MimeKitEmailService : IEmailService
{
    private readonly SmtpClient client;

    public MimeKitEmailService(SmtpClient client)
    {
        this.client = client;
    }

    public async Task SendEmail(string recipient, EmailTemplate template, EmailContent emailContent)
    {
        var message = CreateEmailMessage(recipient, template.GenerateContent(emailContent));
        await SendAsync(message);
    }

    public async Task SendEmail<T>(string recipient, SEmailTemplate<T> template, EmailContent<T> emailContent)
    {
        var message = CreateEmailMessage(recipient, template.GenerateContent(emailContent));
        await SendAsync(message);
    }

    private MimeMessage CreateEmailMessage(string recipient, string content)
    {
        var message = new MimeMessage();
        message.From.Add(new MailboxAddress("ZY", "zy1767992919@163.com"));
        message.To.Add(new MailboxAddress("", recipient));
        message.Subject = "来自ZY知识库通知~";
        message.Body = new TextPart("html")
        {
            Text = content
        };

        return message;
    }

    private async Task SendAsync(MimeMessage message)
    {
        await client.SendAsync(message);
        await client.DisconnectAsync(true);
    }
}

创建工厂类

配置

将邮箱信息存放在appsettings.json文件中方便统一管理

{
  "Email": {
    "Address": "你的邮箱",
    "Password": "授权码"
  }
}

然后创建一个类对应上述参数

public class EmailConfig
{
    public string Address { get; set; }
    public string Password { get; set; }
}

Program.cs文件中绑定EmailConfig类,添加到容器中

builder.Services.Configure<EmailConfig>(builder.Configuration.GetSection("Email"));

工厂类

创建EmailServiceFactory工厂类用于实例化EmailService

  1. 网易:smtp.163.com
  2. QQ:smtp.qq.com

EmailServiceFactory类中注入IOptions<EmailConfig>来邮箱信息配置

public class EmailServiceFactory
{
    private readonly EmailConfig emailConfig;
    public EmailServiceFactory(IOptions<EmailConfig> emailConfigOptions)
    {
        emailConfig = emailConfigOptions.Value;
    }
    public async Task<IEmailService> CreateEmailService()
    {
        var client = new SmtpClient();
        // configure the client
        await client.ConnectAsync("smtp.163.com", 465, true);
        await client.AuthenticateAsync(emailConfig.Address, emailConfig.Password);

        return new MimeKitEmailService(client);
    }
}

注册EmailServiceFactory服务

builder.Services.AddTransient<EmailServiceFactory>();

发送邮件

声明 IEmailServiceEmailServiceFactory变量,然后使用 emailServiceFactoryCreateEmailService 方法异步创建一个 IEmailService 对象用于创建邮箱通信,并将其赋给 emailService 变量,然后new一个模板对象,最后调用emailServiceSendEmail方法发送邮件文章来源地址https://www.toymoban.com/news/detail-534834.html

private IEmailService emailService;
private readonly EmailServiceFactory _emailServiceFactory;

public LinkExchangeService(MyDbContext myDbContext,
        EmailServiceFactory emailServiceFactory)
 {
     _myDbContext = myDbContext;
     _emailServiceFactory = emailServiceFactory;
 }

public async Task SendEmailOnAdd(LinkExchange item)
{
    //创建邮箱连接
    emailService = await _emailServiceFactory.CreateEmailService();
    //内容模板
    var template = new LinksNotificationEmailTemplate(); 
    //发送邮件
    await emailService.SendEmail(item.Email, template,
                                 new EmailContent<LinkExchange>()
                                 {
                                     Content = "您好,友链申请已通过!感谢支持,欢迎互访哦~",
                                     Data = item
                                 });
}

参考资料

  • 基于.NetCore开发博客项目 StarBlog - (28) 开发友情链接相关接口 - StarBlog (deali.cn)

到了这里,关于.NET 个人博客-发送邮件优化?的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 论如何本地搭建个人hMailServer邮件服务远程发送邮件无需域名公网服务器?

    🌷🍁 博主猫头虎(🐅🐾)带您 Go to New World✨🍁 🦄 博客首页 ——🐅🐾猫头虎的博客🎐 🐳 《面试题大全专栏》 🦕 文章图文并茂🦖生动形象🐅简单易学!欢迎大家来踩踩~🌺 🌊 《IDEA开发秘籍专栏》 🐾 学会IDEA常用操作,工作效率翻倍~💐 🌊 《100天精通Golang(基础

    2024年01月24日
    浏览(22)
  • .NET 个人博客系统

    之前通过github学习了一个.net core的博客项目,最近也是完成了博客的备案,完善了一下。该项目是传统的MVC项目,可以进行主题的切换,采用Bootstrap进行前台页面的展示,有配套的后台管理系统,可以解析Markdown文件。 ZY知识库 可以将个人的意见评论到该文章,我可以采纳采

    2023年04月11日
    浏览(11)
  • asp.net使用MailMessage发送邮件的方法

     控件名称及ID如下: 书写后台代码之前需要先了解MailMessage类中的各个属性:         From:发件人邮箱地址。 To:收件人的邮箱地址。     CC:抄送人邮箱地址。 Subject:邮件标题。 Body:邮件内容。        Attachments:邮件附件         此外MailMessage还需要用到Smtp

    2024年02月06日
    浏览(15)
  • .NET 个人博客-添加RSS订阅功能

    个人博客系列已经完成了 留言板 文章归档 推荐文章优化 推荐文章排序 博客地址:https://pljzy.top 然后博客开源的原作者也是百忙之中添加了一个名为 RSS订阅 的功能,那么我就来简述一下这个功能是干嘛的,然后照葫芦画瓢实现一下。 来自 chatGPT 的回答 网站的RSS订阅是一种

    2024年02月11日
    浏览(12)
  • .NET 个人博客-给文章添加上标签

    置顶3个且可滚动或切换 推荐改为4个,然后新增历史文章,将推荐的加载更多放入历史文章,按文章发布时间降序排列。 标签功能,可以为文章贴上标签 推荐点赞功能 本篇文章实现文章标签功能 首先需要新增一个标签类Tag,然后Post文章类和Tag标签类的关系是多对多的关系。

    2024年02月12日
    浏览(13)
  • .NET个人博客-使用Back进行消息推送

    我的好友看了我的博客,给我提了个需求,让我搞个网站通知,我开始以为就是评论回复然后发送邮件通知。不过他告诉我网站通知是,当有人评论或者留言后,会通知到我这边来,消息是实时通知的,他说用的是Back,不需要发邮件,然后发了个GitHub链接给我,我觉得还不错

    2024年02月16日
    浏览(13)
  • 基于ASP.NET MVC开发的、开源的个人博客系统

    推荐一个功能丰富、易于使用和扩展的开源博客,可以轻松地创建和管理自己的博客。 基于.Net Framework 4.5开发的、开源博客系统,具有丰富的功能,包括文章发布、分类、标签、评论、订阅、统计等功能,同时也可以根据需要进行自定义扩展。 提供了丰富的配置选项和API,

    2024年02月14日
    浏览(12)
  • 现代化个人博客系统 ModStartBlog v7.3.0 首页热门博客,UI优化调整

    ModStart 是一个基于 Laravel 模块化极速开发框架。模块市场拥有丰富的功能应用,支持后台一键快速安装,让开发者能快的实现业务功能开发。 系统完全开源,基于 Apache 2.0 开源协议。 丰富的模块市场,后台一键快速安装 会员模块通用且完整,支持完整的API调用 大文件分片上

    2024年02月11日
    浏览(14)
  • .Net FrameWork 框架下使用System.Net.Mail封装类 发送邮件失败:服务器响应:5.7.1 Client was not authenticated 解决方案

    偶然兴起,想做一个后台监控PLC状态的服务。功能如下:监控到PLC状态值异常后触发邮件推送,状态改变后只推送一次。开始使用的是.net6.0开发框架开发,一切都很顺利,邮件也能正常推送。但由于现场工控机系统不是WIN10 20H2的最新版本,导致系统未安装.Net6.0 Runtime。而我

    2024年02月03日
    浏览(12)
  • 【.NET6 + Vue3 + CentOS7.9 + Docker + Docker-Compose + SSL】个人博客前后端运维部署

    个人博客 前端:https://lujiesheng.cn 个人博客 后端:https://api.lujiesheng.cn 个人博客 运维:https://portainer.lujiesheng.cn 我采用的是 腾讯云轻量应用服务器(2C 4G 8M 80G),配置如下图: 安装镜像选择 CentOS 7.6 64bit: 添加防火墙出入站规则,设置如下图: 把已备案的域名解析到服务器

    2024年02月14日
    浏览(13)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包