步骤

引入Volo.Abp.Emailing 包

并在模块中添加对应的依赖。

    [DependsOn(
        typeof(AbpEmailingModule)
   )]
    public class XXXXModule : AbpModule
    {

添加配置

在appsettings.json中添加如下代码:

"Settings": {
  "Abp.Mailing.Smtp.Host": "127.0.0.1",
  "Abp.Mailing.Smtp.Port": "25",
  "Abp.Mailing.Smtp.UserName": "",
  "Abp.Mailing.Smtp.Password": "",
  "Abp.Mailing.Smtp.Domain": "",
  "Abp.Mailing.Smtp.EnableSsl": "false",
  "Abp.Mailing.Smtp.UseDefaultCredentials": "true",
  "Abp.Mailing.DefaultFromAddress": "noreply@abp.io",
  "Abp.Mailing.DefaultFromDisplayName": "ABP application"
}

这里需要特别注意一下,其中的password项目,不可直接填写,abp要求必须对密码进行加密处理,如果你直接填写密码。在发送邮件时会抛出如下异常:

 The input data is not a complete block.
System.Security.Cryptography.CryptographicException: The input data is not a complete block.
   at Internal.Cryptography.UniversalCryptoDecryptor.UncheckedTransformFinalBlock(Byte[] inputBuffer, Int32 inputOffset, Int32 inputCount)
   at Internal.Cryptography.UniversalCryptoTransform.TransformFinalBlock(Byte[] inputBuffer, Int32 inputOffset, Int32 inputCount)
   at System.Security.Cryptography.CryptoStream.ReadAsyncCore(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken, Boolean useAsync)

参考官方文档,要么,使用ISettingManager 进行配置。如果使用appsettings.json进行配置,就需要自行加密后,填写密文。

这里说下第二种,如何进行加密呢?我们可自己下一段端代码,对密码进行加密,调试方式获取加密字符串后,再把这段代码删除即可。
代码如下_settingDefinitionManager和_settingEncryptionService注入即可,用完再删除就行。

private readonly ISettingEncryptionService _settingEncryptionService;
private readonly ISettingDefinitionManager _settingDefinitionManager;
public TestAppService(
    ISettingEncryptionService settingEncryptionService,
    ISettingDefinitionManager settingDefinitionManager)
{

    _settingEncryptionService = settingEncryptionService;
    _settingDefinitionManager = settingDefinitionManager;
}

public async Task EncryptPwd()
{

    var setting = _settingDefinitionManager.Get(EmailSettingNames.Smtp.Password);
    var psd = _settingEncryptionService.Encrypt(setting,"密码");
}

这样,得到了加密后的密码,配置上就可了。

使用

使用的时候,也是非常简单,直接依赖注入方式注入IEmailSender,然后执行SendAsync接口。

private readonly IEmailSender _emailSender;
public TestAppService(
    IEmailSender emailSender)
{
    _emailSender= emailSender;
}

public async Task SendTest()
{
    await _emailSender.SendAsync("123456789@qq.com",
        "测试",
        "正文内容.....");
}

当然,实际使用中,可能还会用到模板等内容,这里不再赘述,参考官方文档吧。