コード例 #1
0
        /// <summary>
        /// Sends an email to a specified address using a specified template.
        /// </summary>
        /// <param name="toAddress">The address to send the email to.</param>
        /// <param name="template">The template to use for the email.</param>
        public void SendEmail(string toAddress, IEmailTemplate template)
        {
            var message = new MimeMessage();

            message.From.Add(new MailboxAddress(this.Settings.FromEmail));
            message.To.Add(new MailboxAddress(toAddress));

            message.Subject = $"{this.Settings.SubjectPrefix} {template.Subject}";

            message.Body = new TextPart("plain")
            {
                Text = template.GetPlainText()
            };

            using (var client = new SmtpClient())
            {
                // accept all SSL certificates (in case the server supports STARTTLS)
                client.ServerCertificateValidationCallback = (s, c, h, e) => true;

                client.Connect(this.Settings.SmtpHost, this.Settings.SmtpPort, this.Settings.SmtpSslRequired);

                if (this.Settings.NeedsAuthentication)
                {
                    // Note: only needed if the SMTP server requires authentication
                    client.Authenticate(this.Settings.SmtpUsername, this.Settings.SmtpPassword);
                }

                client.Send(message);
                client.Disconnect(true);
            }
        }