Net如何优雅的实现发送邮件服务

使用.NET内置的SmtpClient类

在.NET中,可以通过System.Net.Mail命名空间下的SmtpClient类发送邮件。需要配置SMTP服务器地址、端口、凭据等信息。

具体实现可参考NetCoreKevin的Kevin.Email模块

基于.NET构建的企业级SaaS智能应用架构,采用前后端分离设计,具备以下核心特性:
前端技术:

EmailService实现

using Kevin.Email.dto;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Net.Mime;
using System.Text;
using System.Threading.Tasks;

namespace Kevin.Email
{
    /// <summary>
    /// 邮件服务
    /// </summary>
    public class EmailService : IEmailService, IDisposable
    {
        private readonly EmailSetting _emailSetting;

        private readonly SmtpClient _smtpClient;
        public EmailService(IOptionsMonitor<EmailSetting> config)
        {
            _emailSetting = config.CurrentValue;
            _smtpClient = new(_emailSetting.SmtpServer, _emailSetting.Port);
            _smtpClient.Credentials = new NetworkCredential(_emailSetting.AccountName, _emailSetting.AccountPassword);
            _smtpClient.EnableSsl = true;
            _smtpClient.UseDefaultCredentials = false;
            _smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
        }

        public void Dispose()
        {
            _smtpClient.Dispose();
        }

        /// <summary>
        /// 发送邮件
        /// </summary>
        /// <param name="email"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<bool> SendEmail(SendEmailDto email)
        {  
            using (MailMessage message = new())
            {
                foreach (var filePath in email.FileList)
                {
                    Attachment data = new(filePath.Key, MediaTypeNames.Application.Octet)
                    {
                        Name = filePath.Value
                    };
                    message.Attachments.Add(data);
                }
                message.From = new(_emailSetting.AccountName, email.FromDisplayName);
                foreach (var toAddress in email.ToAddresses)
                {
                    message.To.Add(new MailAddress(toAddress));
                }
                message.Subject = email.Subject;
                message.Body = email.Body;
                message.BodyEncoding = System.Text.Encoding.UTF8;
                message.IsBodyHtml = email.IsBodyHtml;
                await _smtpClient.SendMailAsync(message);
            }
            return true;
        }
    }
}

var smtpClient = new SmtpClient("smtp.example.com")
{
    Port = 587,
    Credentials = new NetworkCredential("username", "password"),
    EnableSsl = true,
};

var mailMessage = new MailMessage
{
    From = new MailAddress("from@example.com"),
    Subject = "Subject",
    Body = "<h1>Hello</h1>",
    IsBodyHtml = true,
};
mailMessage.To.Add("to@example.com");

smtpClient.Send(mailMessage);

使用MailKit库

MailKit是一个更现代、功能更强大的邮件处理库,支持更多协议和高级功能。

var message = new MimeMessage();
message.From.Add(new MailboxAddress("Sender Name", "from@example.com"));
message.To.Add(new MailboxAddress("Recipient Name", "to@example.com"));
message.Subject = "Subject";

var builder = new BodyBuilder();
builder.HtmlBody = "<h1>Hello</h1>";

message.Body = builder.ToMessageBody();

using var client = new SmtpClient();
client.Connect("smtp.example.com", 587, SecureSocketOptions.StartTls);
client.Authenticate("username", "password");
client.Send(message);
client.Disconnect(true);

配置依赖注入

在ASP.NET Core中,可以通过依赖注入方式配置邮件服务。

services.AddTransient<IEmailSender, EmailSender>();
services.Configure<EmailSettings>(Configuration.GetSection("EmailSettings"));

实现EmailSender类:

public class EmailSender : IEmailSender
{
    private readonly EmailSettings _emailSettings;

    public EmailSender(IOptions<EmailSettings> emailSettings)
    {
        _emailSettings = emailSettings.Value;
    }

    public async Task SendEmailAsync(string email, string subject, string message)
    {
        // 使用MailKit或SmtpClient实现发送逻辑
    }
}

使用FluentEmail库

FluentEmail提供了流畅的API来构建和发送邮件。

var email = Email
    .From("from@example.com")
    .To("to@example.com")
    .Subject("Subject")
    .Body("Hello");

email.Send();

处理异步发送

对于Web应用,建议使用异步方式发送邮件以避免阻塞请求线程。

public async Task SendEmailAsync(string to, string subject, string body)
{
    using var smtpClient = new SmtpClient("smtp.example.com");
    var mailMessage = new MailMessage("from@example.com", to, subject, body);
    await smtpClient.SendMailAsync(mailMessage);
}

配置邮件模板

使用Razor模板引擎生成邮件内容,保持视图和逻辑分离。

var template = "Hello @Model.Name, welcome to our service!";
var result = Razor.Parse(template, new { Name = "John" });
posted @ 2025-12-26 11:11  NetCoreKevin  阅读(146)  评论(0)    收藏  举报