Step by step Vue + element front end application development (33) — mail parameter configuration and template mail sending processing

Time:2021-9-17

In system processing, it is sometimes necessary to send e-mail to notify users, such as e-mail confirmation of new users, password retrieval, and routine subscription messages, notifications and other content processing, which can be processed by e-mail. This essay introduces how to realize the mail parameter configuration management of the system and send mail based on mail template combined with Vue + element front end.

1. Configuration management of mail parameters

E-mail parameters generally need to be configured, such as user name, password, e-mail address, display name, and other necessary configurations for e-mail. Generally, we can configure general parameters through interface management, as shown in the following interface.

The login password is now generally the authorized login password rather than the original account password. Take 163 as an example, you can add an authorization password to the settings.

 

For the configuration management of front-end parameters, we build an API class to call the API interface of ABP back-end, as shown below.

 

The code for displaying mail parameter data in the view form is as follows.

showAbpEmail() {
      this.resetForm('emailForm')
      setting.GetEmailSettingsForApplication().then(data => {
        if (data.result) {
          Object.assign(this.abpEmailForm, data.result)
        }
        This.isabpemail = true // editing status
      })
    },

 

2. Sending and processing of ABP backend mail

After the system parameters are configured, we need to send mail according to these mail parameters. The ABP framework is based on the implementation of. Net core. When we send mail, we need to add a dependency of abp.mailkit, as shown below.

Then, add the corresponding abpmailkitmodule dependency on the module dependency.

Generally speaking, when sending mail, we also need to rewrite the configuration processing item of defaultmailkitsmtpbuilder to customize the sending processing process.

/// 
    ///Override the default smtpbuilder class
    /// 
    public class MyMailKitSmtpBuilder : DefaultMailKitSmtpBuilder
    {
        private readonly ISmtpEmailSenderConfiguration _smtpEmailSenderConfiguration;
        private readonly IAbpMailKitConfiguration _abpMailKitConfiguration;
        public MyMailKitSmtpBuilder(ISmtpEmailSenderConfiguration smtpEmailSenderConfiguration, IAbpMailKitConfiguration abpMailKitConfiguration)
            : base(smtpEmailSenderConfiguration, abpMailKitConfiguration)
        {
            _smtpEmailSenderConfiguration = smtpEmailSenderConfiguration;
            _abpMailKitConfiguration = abpMailKitConfiguration;
        }

        /// 
        ///Configure send processing
        /// 
        /// 
        protected override void ConfigureClient(SmtpClient client)
        {
            client.CheckCertificateRevocation = false;
            client.ServerCertificateValidationCallback = (sender, certificate, chain, errors) => true;

            client.Connect(_smtpEmailSenderConfiguration.Host, _smtpEmailSenderConfiguration.Port, GetSecureSocketOption());

            if (_smtpEmailSenderConfiguration.UseDefaultCredentials)
            {
                return;
            }

            var username = _smtpEmailSenderConfiguration.UserName;
            var password = _smtpEmailSenderConfiguration.Password;
            //password = SimpleStringCipher.Instance.Decrypt(originalPass);// If the custom configuration mysmtpemailsenderconfiguration is not rewritten, the password needs to be decrypted
            client.Authenticate(username, password);

            //base.ConfigureClient(client);
        }
    }

However, in the base class processing, the default mail configuration password reads information directly from the database without encryption. For example, the implementation of the base class smtpemailsenderconfiguration is as follows.

However, the password of our application is encrypted, so we need to rewrite this configuration item to decrypt the corresponding password.

/// 
    ///Mail sending parameter configuration class
    /// 
    public class MySmtpEmailSenderConfiguration : SmtpEmailSenderConfiguration
    {
        public MySmtpEmailSenderConfiguration(ISettingManager settingManager) : base(settingManager)
        {

        }

        /// 
        ///To rewrite password processing, you need to decrypt the password
        /// 
        public override string Password => SimpleStringCipher.Instance.Decrypt(GetNotEmptySettingValue(EmailSettingNames.Smtp.Password));
    }

Finally, initialize the corresponding custom sending and custom configuration item processing classes in the module.

In this way, the default injected email sending interface is normal. Next, we can send the content according to the email template.

 

3. Processing of mail template

The general mail template is an independent file method. Some preset contents are defined in the file, and then these variables can be replaced during actual processing.

For the content replacement of e-mail template, I like to use the template engine to process the variable replacement. Generally, I use nvelocity to process it.

I introduced some knowledge about nvelocity earlier. You can refer to:

Several ways to generate content using nvelocity

Powerful template engine, open source software “nvelocity”

Custom template generation for database2sharp version update 》

Using nvelocity 0.5 to realize the automatic generation of server-side pages 》

For example, I define a connection in the text: http://www.iqidi.com/h5/EmailValidate?callback= ${callback}   Where ${callback} is the variable definition, which can be replaced during operation.

We define some mail file templates in the host project, as shown below.

 

Then inject the corresponding mail sending interface into the used application service class for use.

 

The specific mail is to read the template content, replace the variables, and then call the interface to send the mail.

/// 
        ///Send verification email
        /// 
        /// 
        public async Task SendEmailValidate(SendEmailActivationLinkDto input)
        {
            var user = await GetUserByChecking(input.EmailAddress);
            //user.SetNewEmailConfirmationCode();

            #Region generates the message body according to the template

            //Construction processing using relative paths
            string template = string.Format("/UploadFiles/Email/EmailValidate.html");
            var helper = new NVelocityHelper(template);
            //${Title} ${content} ${address} ${date}
            Var tile = "mailbox verification notification";
            helper.AddKeyValue("title", tilte);
            helper.AddKeyValue("callname", "");
            helper.AddKeyValue("date", DateTime.Now.ToLongDateString());

            //Mailbox check code
            var callback = Guid.NewGuid().ToString();
            helper.AddKeyValue("callback", callback);

            var html = helper.ExecuteString();

            #endregion

            #Region build mail content object to send mail
            string toEmail = "[email protected]";

            await _emailSender.SendAsync(new System.Net.Mail.MailMessage
            { 
                To = { toEmail },
                Subject = tilte,
                Body = html,
                IsBodyHtml = true
            });

            #endregion

            Loghelper.logger.info (string. Format ("verification email sent to: {0}, {1}", toemail, "email sent successfully");
        }

For the convenience of handling the template content, we put the rules in the auxiliary class   It can be processed in the nvelocityhelper.

The above is the process code of sending template email.

After sending the mail successfully, we can view the corresponding mail in the mailbox. We generally define different mail templates according to our business needs.

After the mail is sent successfully, the effect of viewing the mail is as follows.