1、在EntityFramework项目中:Migrations/SeedData/DefaultSettingsCreator.cs中配置邮件服务:
public void Create() { #region Emailing string mail_smtp = ConfigurationManager.AppSettings["mail_smtp"]; string mail_main = ConfigurationManager.AppSettings["mail_main"]; string mail_pwd = ConfigurationManager.AppSettings["mail_pwd"]; string mail_port = ConfigurationManager.AppSettings["mail_port"]; string mail_ssl = ConfigurationManager.AppSettings["mail_ssl"]; string mail_name = ConfigurationManager.AppSettings["mail_name"]; AddSettingIfNotExists(EmailSettingNames.DefaultFromAddress, mail_main); AddSettingIfNotExists(EmailSettingNames.DefaultFromDisplayName, mail_name); AddSettingIfNotExists(EmailSettingNames.Smtp.Port, mail_port); AddSettingIfNotExists(EmailSettingNames.Smtp.Host, mail_smtp); AddSettingIfNotExists(EmailSettingNames.Smtp.UserName, mail_main); AddSettingIfNotExists(EmailSettingNames.Smtp.Password, mail_pwd); AddSettingIfNotExists(EmailSettingNames.Smtp.Domain, ""); AddSettingIfNotExists(EmailSettingNames.Smtp.EnableSsl, mail_ssl); AddSettingIfNotExists(EmailSettingNames.Smtp.UseDefaultCredentials, "false"); #endregion //Languages AddSettingIfNotExists(LocalizationSettingNames.DefaultLanguage, "en"); }
2、在Web项目中config配置邮件服务器
<appSettings> <add key="webpages:Version" value="3.0.0.0" /> <add key="webpages:Enabled" value="false" /> <add key="ClientValidationEnabled" value="true" /> <add key="UnobtrusiveJavaScriptEnabled" value="true" /> <!-- 邮件服务 --> <add key="mail_smtp" value="smtp.exmail.qq.com" /> <add key="mail_main" value="xxx@xxx.com" /> <add key="mail_pwd" value="xxx" /> <add key="mail_port" value="123" /> <add key="mail_ssl" value="true" /> <add key="mail_name" value="admin" /> </appSettings>
3、在项目Core中nuget安装:AbpMailKit,然后在Core中找到 xxxCoreModule.cs
using Abp.MailKit;
[DependsOn(typeof(AbpZeroCoreModule),typeof(AbpMailKitModule))] public class AbpFrameworkCoreModule : AbpModule{...}
4、在Core项目下面建一个类TaskManager
using Abp.Domain.Services; using Abp.Net.Mail; using Abp.Net.Mail.Smtp; namespace AbpFramework.Base { public class TaskManager : IDomainService { private readonly IEmailSender _emailSender; public TaskManager( IEmailSender emailSender, ISmtpEmailSenderConfiguration smtpEmialSenderConfigtion ) { _emailSender = emailSender; } /// <summary> /// 发送邮件 /// </summary> /// <param name="emailAddress">目标邮箱</param> /// <param name="subject">邮件标题</param> /// <param name="body">邮件内容</param> public void SendMail(string emailAddress, string subject, string body) { try { //TODO:发送一份邮件通知,所有调用该方法的地方的文档都需要坚持调整,暂时屏蔽邮件异常 _emailSender.SendAsync( to: emailAddress, subject: subject, body: body, isBodyHtml: true ); } catch (System.Exception ex) { } } } }
5、调用,在Application项目中
[AbpAuthorize] public class DispatchAppService : ApplicationService { private readonly TaskManager _taskManager; public DispatchAppService(TaskManager taskManager) { _taskManager = taskManager; } public void SendMail() { _taskManager.SendMail("abc@abc.com", "标题", "Html内容"); } }