I am trying to send email using smtp to multiple users from asp.net core web api with angular 2.0. but its throwing CORS error

367 views Asked by At

bellow is my error:

Access to XMLHttpRequest at 'https://localhost:44359/api/ClientCandidateBulkStatusUpdate' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I made settings in startup.cs like:

public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors(options =>
        {
            options.AddPolicy("CorsPolicy",
                builder => builder.AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader()
                // .SetIsOriginAllowed(origin => true)//allow any origin
                .AllowCredentials());
               // .Build());
                
        });
                    
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); 
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseHsts();
        }
        var builder = new ConfigurationBuilder()
        .SetBasePath(env.ContentRootPath)
        .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
        .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);

        builder.AddEnvironmentVariables();
        builder.Build();
        app.UseCors("CorsPolicy");
        ////app.UseCors(builder1 => builder1
        ////    .AllowAnyOrigin()
        ////    .AllowAnyMethod()
        ////    .AllowAnyHeader()
        ////    .SetIsOriginAllowed(origin => true)//allow any origin
        ////    .AllowCredentials());// allow credentials
        
        app.UseHttpsRedirection();
        app.UseMvc();
    }

I enabled CORS on Controller like

 [Route("api/[controller]")]
[ApiController]
[EnableCors("CorsPolicy")]
public class ClientCandidateBulkStatusUpdateController : ControllerBase
{}

my send mail code is:

public void Sendmail(String MailFrom, String Mailto, String Subject, String Body, String CC = "", Boolean Copy = false)
    {
        DataTable EmailSettingsDT = new DataTable();
        EmailSettingsDT = GetEmailSettings();
        if (EmailSettingsDT.Rows.Count > 0)
        {
            string a = EmailSettingsDT.Rows[0]["SMTPHost"].ToString();
            int port = Convert.ToInt32(EmailSettingsDT.Rows[0]["SMTPPort"]);
            using (SmtpClient smtp = new SmtpClient(EmailSettingsDT.Rows[0]["SMTPHost"].ToString()))
            {

                var basicCredential = new NetworkCredential(EmailSettingsDT.Rows[0]["SMTPUsername"].ToString(), EmailSettingsDT.Rows[0]["SMTPPassword"].ToString());
                smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
                smtp.EnableSsl = Convert.ToBoolean(EmailSettingsDT.Rows[0]["IS_SSL"].ToString());
                smtp.UseDefaultCredentials = false;
                smtp.Credentials = basicCredential;
                smtp.Port = Convert.ToInt32(EmailSettingsDT.Rows[0]["SMTPPort"].ToString());
                var mail = new MailMessage();
                mail.From = new MailAddress(EmailSettingsDT.Rows[0]["SMTPUsername"].ToString(), EmailSettingsDT.Rows[0]["DisplayName"].ToString());
                mail.To.Add(Mailto);
                if (Copy == true)
                {
                    mail.CC.Add(CC);

                }
                mail.IsBodyHtml = true;
                mail.Subject = Subject;
                mail.Body = Body;
                smtp.Send(mail);
                mail.Dispose();
                smtp.Dispose();
            }
            //var smtp = new SmtpClient(EmailSettingsDT.Rows[0]["SMTPHost"].ToString());

        }
    }
SMTP PORT:587, HOST:smtp.gmail.com

My angular code is:

UpdateClientReviewCandidateStatus(Data: any) {
const header = new Headers({ 'Content-type': 'application/json' });  
return this._http.post(this.apiUrl + 'ClientCandidateBulkStatusUpdate', Data, httpOptions).pipe(map((data: Response) => <any>data))

}

I tried with commented code also still not solved issue. SMTP is having limitation to send email for 100. I have not reached limit still it is throwing while sending bulk email. Some emails like 5 or 10 are sending but else get structed with above CORS error. I tried to send mail using MailKit and MailChimp also but no solution found. plz can anyone help me to solve this error.

thanks in advance.

0

There are 0 answers