Base solution for your next web application
Starts in:
01 DAYS
01 HRS
01 MIN
01 SEC
Open Closed

Email Configuration #5328


User avatar
0
jehadk created

We Have problem in sending the email Version# AspNetZeroCore v5.3.0

An error occurred while attempting to establish an SSL or TLS connection.

The SSL certificate presented by the server is not trusted by the system for one or more of the following reasons:

  1. The server is using a self-signed certificate which cannot be verified.
  2. The local system is missing a Root or Intermediate certificate needed to verify the server's certificate.
  3. The certificate presented by the server is expired or invalid.

See <a class="postlink" href="https://github.com/jstedfast/MailKit/blob/master/FAQ.md#InvalidSslCertificate">https://github.com/jstedfast/MailKit/bl ... ertificate</a> for possible solutions.


12 Answer(s)
  • User Avatar
    0
    maliming created
    Support Team

    You can refer to this reply to solve. [https://github.com/aspnetboilerplate/aspnetboilerplate/issues/3547#issuecomment-400181114])

  • User Avatar
    0
    jehadk created

    <cite>maliming: </cite> You can refer to this reply to solve. [https://github.com/aspnetboilerplate/aspnetboilerplate/issues/3547#issuecomment-400181114])

    Error MailKit.Security.AuthenticationException: 'AuthenticationInvalidCredentials: 5.7.3

    Authentication unsuccessful' /// Define new class public class MyMailKitSmtpBuilder : DefaultMailKitSmtpBuilder { public MyMailKitSmtpBuilder(ISmtpEmailSenderConfiguration smtpEmailSenderConfiguration) : base(smtpEmailSenderConfiguration) { }

        protected override void ConfigureClient(SmtpClient client)
        {
            client.ServerCertificateValidationCallback = (sender, certificate, chain, errors) => true;
    
            base.ConfigureClient(client);
        }
    }
    

    I implement in the PreInitialize below code /////////PreInitialize// Configuration.ReplaceService(typeof(IEmailSenderConfiguration), () => { Configuration.IocManager.IocContainer.Register( Component.For<IEmailSenderConfiguration, ISmtpEmailSenderConfiguration>() .ImplementedBy<BarznWebSmtpEmailSenderConfiguration>() .LifestyleTransient() ); }); Configuration.ReplaceService<IMailKitSmtpBuilder, MyMailKitSmtpBuilder>(DependencyLifeStyle.Transient); //////////////////////////////////////////////////////////////

  • User Avatar
    0
    ryancyq created
    Support Team

    Hi @jehadk,

    Please override ConfigureClient as follow:

    protected override void ConfigureClient(SmtpClient client)
    {
        client.Connect(
            _smtpEmailSenderConfiguration.Host,
            _smtpEmailSenderConfiguration.Port,
            SecureSocketOptions.Auto
        );
    
        if (_smtpEmailSenderConfiguration.UseDefaultCredentials)
        {
            return;
        }
    
        client.Authenticate(
            _smtpEmailSenderConfiguration.UserName,
            _smtpEmailSenderConfiguration.Password
        );
    }
    

    As mentioned in [https://github.com/aspnetboilerplate/aspnetboilerplate/blob/dev/src/Abp.MailKit/DefaultMailKitSmtpBuilder.cs#L35])

  • User Avatar
    0
    jehadk created

    Is this right ?? can you please check below Note I cannot define _abpMailKitConfiguration but the error appear System.Net.Sockets.SocketException: 'A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 172.16.2.119:25'

    public class DefaultMailKitSmtpBuilder : IMailKitSmtpBuilder, ITransientDependency
    {
        private readonly ISmtpEmailSenderConfiguration _smtpEmailSenderConfiguration;
        //private readonly IAbpMailKitConfiguration _abpMailKitConfiguration;
    
        public DefaultMailKitSmtpBuilder(ISmtpEmailSenderConfiguration smtpEmailSenderConfiguration)
        {
            _smtpEmailSenderConfiguration = smtpEmailSenderConfiguration;
            
        }
    
        public virtual SmtpClient Build()
        {
            var client = new SmtpClient();
    
            try
            {
                ConfigureClient(client);
                return client;
            }
            catch
            {
                client.Dispose();
                throw;
            }
        }
    
        protected virtual void ConfigureClient(SmtpClient client)
        {
            client.Connect(
                _smtpEmailSenderConfiguration.Host,
                _smtpEmailSenderConfiguration.Port,
                GetSecureSocketOption()
            );
    
            if (_smtpEmailSenderConfiguration.UseDefaultCredentials)
            {
                return;
            }
    
            client.Authenticate(
                _smtpEmailSenderConfiguration.UserName,
                _smtpEmailSenderConfiguration.Password
            );
        }
    
        protected virtual SecureSocketOptions GetSecureSocketOption()
        {
         
            return _smtpEmailSenderConfiguration.EnableSsl
                ? SecureSocketOptions.SslOnConnect
                : SecureSocketOptions.StartTlsWhenAvailable;
        }
    }
            //if (DebugHelper.IsDebug)
            //{
            //    //Disabling email sending in debug mode
            //    Configuration.ReplaceService&lt;IEmailSender, NullEmailSender&gt;(DependencyLifeStyle.Transient);
            //}
    
            Configuration.ReplaceService(typeof(IEmailSenderConfiguration), () =>
            {
                Configuration.IocManager.IocContainer.Register(
                    Component.For&lt;IEmailSenderConfiguration, ISmtpEmailSenderConfiguration&gt;()
                             .ImplementedBy&lt;BarznWebSmtpEmailSenderConfiguration&gt;()
                             .LifestyleTransient()
                );
            });
            Configuration.ReplaceService&lt;IMailKitSmtpBuilder, DefaultMailKitSmtpBuilder&gt;(DependencyLifeStyle.Transient);
    
  • User Avatar
    0
    maliming created
    Support Team
    Configuration.ReplaceService<IMailKitSmtpBuilder, MyMailKitSmtpBuilder>(DependencyLifeStyle.Transient);
    

    Just call ReplaceService to replace the built-in service.

    [https://aspnetboilerplate.com/Pages/Documents/Startup-Configuration#replacing-built-in-services])

  • User Avatar
    0
    jehadk created

    Dear I commit the ReplaceService for IEmailSenderConfiguration but the password sent intercepted, so I back the code as below but in same time I have error
    MailKit.Security.AuthenticationException: 'AuthenticationInvalidCredentials: 5.7.3 Authentication unsuccessful'

    public class DefaultMailKitSmtpBuilder : IMailKitSmtpBuilder, ITransientDependency { private readonly ISmtpEmailSenderConfiguration _smtpEmailSenderConfiguration; //private readonly IAbpMailKitConfiguration _abpMailKitConfiguration;

        public DefaultMailKitSmtpBuilder(ISmtpEmailSenderConfiguration smtpEmailSenderConfiguration)
        {
            _smtpEmailSenderConfiguration = smtpEmailSenderConfiguration;
    
        }
    
        public virtual SmtpClient Build()
        {
            var client = new SmtpClient();
    
            try
            {
                ConfigureClient(client);
                return client;
            }
            catch
            {
                client.Dispose();
                throw;
            }
        }
    
        protected virtual void ConfigureClient(SmtpClient client)
        {
            client.Connect(
            _smtpEmailSenderConfiguration.Host,
            _smtpEmailSenderConfiguration.Port,SecureSocketOptions.None
            
            );
    
            if (_smtpEmailSenderConfiguration.UseDefaultCredentials)
            {
                return;
            }
            
            
        client.Authenticate(
            _smtpEmailSenderConfiguration.UserName,
            _smtpEmailSenderConfiguration.Password
            );
        }
    
        protected virtual SecureSocketOptions GetSecureSocketOption()
        {
    
            return _smtpEmailSenderConfiguration.EnableSsl
            ? SecureSocketOptions.SslOnConnect
            : SecureSocketOptions.StartTlsWhenAvailable;
        }
    }
    [DependsOn(
        typeof(AbpZeroCoreModule),
        typeof(AbpZeroLdapModule),
        typeof(AbpAutoMapperModule),
        typeof(AbpAspNetZeroCoreModule),
        typeof(AbpMailKitModule))]
    public class BarznWebCoreModule : AbpModule
    {
        public override void PreInitialize()
        {
            //workaround for issue: &lt;a class=&quot;postlink&quot; href=&quot;https://github.com/aspnet/EntityFrameworkCore/issues/9825&quot;&gt;https://github.com/aspnet/EntityFramewo ... ssues/9825&lt;/a&gt;
            //related github issue: &lt;a class=&quot;postlink&quot; href=&quot;https://github.com/aspnet/EntityFrameworkCore/issues/10407&quot;&gt;https://github.com/aspnet/EntityFramewo ... sues/10407&lt;/a&gt;
            AppContext.SetSwitch("Microsoft.EntityFrameworkCore.Issue9825", true);
    
            Configuration.Auditing.IsEnabledForAnonymousUsers = true;
    
            //Declare entity types
            Configuration.Modules.Zero().EntityTypes.Tenant = typeof(Tenant);
            Configuration.Modules.Zero().EntityTypes.Role = typeof(Role);
            Configuration.Modules.Zero().EntityTypes.User = typeof(User);
    
            BarznWebLocalizationConfigurer.Configure(Configuration.Localization);
    
            //Adding feature providers
            Configuration.Features.Providers.Add&lt;AppFeatureProvider&gt;();
    
            //Adding setting providers
            Configuration.Settings.Providers.Add&lt;AppSettingProvider&gt;();
    
            //Adding notification providers
            Configuration.Notifications.Providers.Add&lt;AppNotificationProvider&gt;();
    
            //Enable this line to create a multi-tenant application.
            Configuration.MultiTenancy.IsEnabled = BarznWebConsts.MultiTenancyEnabled;
            
            //Enable LDAP authentication (It can be enabled only if MultiTenancy is disabled!)
            //Configuration.Modules.ZeroLdap().Enable(typeof(AppLdapAuthenticationSource));
    
            //Configure roles
            AppRoleConfig.Configure(Configuration.Modules.Zero().RoleManagement);
    
            //if (DebugHelper.IsDebug)
            //{
            //    //Disabling email sending in debug mode
            //    Configuration.ReplaceService&lt;IEmailSender, NullEmailSender&gt;(DependencyLifeStyle.Transient);
            //}
    
    
            //Configuration.ReplaceService(typeof(IEmailSenderConfiguration), () =>
            //{
            //    Configuration.IocManager.IocContainer.Register(
            //        Component.For&lt;IEmailSenderConfiguration, ISmtpEmailSenderConfiguration&gt;()
            //                 .ImplementedBy&lt;BarznWebSmtpEmailSenderConfiguration&gt;()
            //                 .LifestyleTransient()
            //    );
            //});
            Configuration.ReplaceService(typeof(IEmailSenderConfiguration), () =>
            {
                Configuration.IocManager.IocContainer.Register(
                    Component.For&lt;IEmailSenderConfiguration, ISmtpEmailSenderConfiguration&gt;()
                             .ImplementedBy&lt;BarznWebSmtpEmailSenderConfiguration&gt;()
                             .LifestyleTransient()
                );
            });
            Configuration.ReplaceService&lt;IMailKitSmtpBuilder, DefaultMailKitSmtpBuilder&gt;(DependencyLifeStyle.Transient);
    
            Configuration.Caching.Configure(FriendCacheItem.CacheName, cache =>
            {
                cache.DefaultSlidingExpireTime = TimeSpan.FromMinutes(30);
            });
    
            Configuration.Caching.Configure(PaymentCacheItem.CacheName, cache =>
            {
                cache.DefaultSlidingExpireTime = TimeSpan.FromMinutes(BarznWebConsts.PaymentCacheDurationInMinutes);
            });
        }
    
        public override void Initialize()
        {
            IocManager.RegisterAssemblyByConvention(typeof(BarznWebCoreModule).GetAssembly());
        }
    
        public override void PostInitialize()
        {
            IocManager.RegisterIfNot&lt;IChatCommunicator, NullChatCommunicator&gt;();
    
            IocManager.Resolve&lt;ChatUserStateWatcher&gt;().Initialize();
            IocManager.Resolve&lt;AppTimes&gt;().StartupTime = Clock.Now;
        }
    }
    

    }

    public class BarznWebSmtpEmailSenderConfiguration : SmtpEmailSenderConfiguration { public BarznWebSmtpEmailSenderConfiguration(ISettingManager settingManager) : base(settingManager) {

        }
    
        public override string Password => SimpleStringCipher.Instance.Decrypt(GetNotEmptySettingValue(EmailSettingNames.Smtp.Password));
    }
    
  • User Avatar
    0
    maliming created
    Support Team

    Hi jehadk

    You can download a template here [https://aspnetboilerplate.com/Templates]) Simply call the recurring problem and send the project to me at <a href="mailto:[email protected]">[email protected]</a>

  • User Avatar
    0
    ismcagdas created
    Support Team

    The final problem here is : Authentication unsuccessful Be sure that you are using the correct credentials.

  • User Avatar
    0
    maliming created
    Support Team

    ismcagdas

    Yesterday I received a project for jehadk.

    client.Connect( _smtpEmailSenderConfiguration.Host, _smtpEmailSenderConfiguration.Port, MailKit.Security.SecureSocketOptions.Auto ); This will resolve the certificate issue encountered.

    But the current prompt: "AuthenticationInvalidCredentials: 5.7.3 authentication failed"

  • User Avatar
    0
    ismcagdas created
    Support Team

    Thanks @maliming :). I think @jehadk should investigate "authentication failed" error. This doesn't seem like a problem related to AspNet Zero.

  • User Avatar
    0
    jehadk created

    OK, Thanks for your support.

    How I can attach file to the email? does Frame Work support the attachment file when send the email ??

  • User Avatar
    0
    ryancyq created
    Support Team

    You can do something like this

    MailMessage mail = new MailMessage
    {
        Subject = "Subject",
        Body = "Message",
        IsBodyHtml = true
    };
    
    mail.Attachments.Add(new Attachment(stream, "invoice.pdf"));
    
    await this._emailSender.SendAsync(mail);
    

    Refer to <a class="postlink" href="https://github.com/aspnetboilerplate/aspnetboilerplate/issues/2442">https://github.com/aspnetboilerplate/as ... ssues/2442</a>