ABP中对邮件的封装主要集成在Abp.Net.Mail
和Abp.Net.Mail.Smtp
命名空间下,相应源码在此。
分析可以看出主要由以下几个核心类组成:
SettingProvider
,对EmailSettingNames
中定义的参数项进行设置。
EmailSenderConfiguration
,用来读取设置的支持Smtp协议邮件相关参数项。
EmailSenderBase
,实现了ISmtpEmailSender
接口。该类就是基于SMTP协议进行邮件发送。提供了SendEmailAsync(MailMessage mail)
和SendEmail(MailMessage mail)
,同步异步两种发送邮件的方法。
想具体了解源码的实现方式,建议参考以下两篇博文:
结合ABP源码实现邮件发送功能
ABP源码分析七:Setting 以及 Mail
在以EntityFramework
结尾的项目中的DefaultSettingsCreator
中添加默认设置,然后在程序包管理控制台执行Update-DataBase
,这样即可把种子数据更新到数据库中。
代码中我是以QQ邮箱设置,有几点需要注意:
首先,在Service中通过构造函数注入ISmtpEmailSenderConfiguration
private readonly IRepository<Task> _taskRepository;
private readonly IRepository<User, long> _userRepository;
private readonly ISmtpEmailSenderConfiguration _smtpEmialSenderConfig;
/// <summary>
///In constructor, we can get needed classes/interfaces.
///They are sent here by dependency injection system automatically.
/// </summary>
public TaskAppService(IRepository<Task> taskRepository, IRepository<User, long> userRepository,
ISmtpEmailSenderConfiguration smtpEmialSenderConfigtion)
{
_taskRepository = taskRepository;
_userRepository = userRepository;
_smtpEmialSenderConfig = smtpEmialSenderConfigtion;
}
在需要发送邮件的地方调用SmtpEmailSender
类的发送方法即可。
SmtpEmailSender emailSender = new SmtpEmailSender(_smtpEmialSenderConfig);
string message = "You hava been assigned one task into your todo list.";
emailSender.Send("ysjshengjie@qq.com", task.AssignedPerson.EmailAddress, "New Todo item", message);
直接上代码示例:
INotificationPublisher
/// <summary>
///In constructor, we can get needed classes/interfaces.
///They are sent here by dependency injection system automatically.
/// </summary>
public TaskAppService(IRepository<Task> taskRepository, IRepository<User, long> userRepository,
ISmtpEmailSenderConfiguration smtpEmialSenderConfigtion, INotificationPublisher notificationPublisher)
{
_taskRepository = taskRepository;
_userRepository = userRepository;
_smtpEmialSenderConfig = smtpEmialSenderConfigtion;
_notificationPublisher = notificationPublisher;
}
INotificationPublisher
接口提供的Publish
或PublishAsync
方法即可;我们先来看看需要用到参数。
注意
string message = "You hava been assigned one task into your todo list.";
_notificationPublisher.Publish("NewTask", new MessageNotificationData(message), null,NotificationSeverity.Info, new[] {task.AssignedPerson.ToUserIdentifier()});