What is the process for sending an email using Angular 5 to an endpoint in ASP.NET Core?

I am attempting to send an email with header information and email details included in the message body.

Here is the code I have tried:

The typescript.
/// <summary> 
/// Sending an email to the client.
/// </summary>
sendEmail() {
    if (this.email.userId) {
        let headers = new Headers();
        headers.append('Content-Type', 'application/json');
        headers.append('Authorization', 'Bearer ' + abp.auth.getToken());

        let url = `${AppConsts.remoteServiceBaseUrl}/EmailComponents/SendEmail?`;

        if (this.email.recipientEmailAddress) {
            url += `recipientEmail=${encodeURIComponent("" + this.email.recipientEmailAddress)}&`;
        }

        if (this.email.subject) {
            url += `subject=${encodeURIComponent("" + this.email.subject)}&`;
        }

        if (this.name) {
            url += `emailTemplate=${encodeURIComponent("" + this.name)}`;
        }

        this.http.post(url, 
        {
            headers: headers,
            message: this.email.body
        })
        .subscribe(result => {
            this.notify.info(`Email sent successfully.`);
        });
    }
}

    The endpoint controller
    /// <summary>
    /// Sends an email containing recipient email address, subject, message, and email template.
    /// </summary>
    /// <param name="recipientEmail">The recipient Email.</param>
    /// <param name="subject">The subject.</param>
    /// <param name="message">The message</param>
    /// <param name="emailTemplate">The email template.</param>
    /// <returns>Asynchronous result.</returns>
    [HttpPost]
    public async Task SendEmail(string recipientEmail, string subject, [FromBody] string message, string emailTemplate)
    {
        var userId = _abpSession.GetUserId();
        var user = await GetCurrentUser(userId);

        if (!string.IsNullOrEmpty(user.EmailAddress))
        {
            //Get smtp details.
            var smtpHost = _emailSmtpSetting.FirstOrDefault(a => a.Name == "SMTP Host");
            var smtpPort = _emailSmtpSetting.FirstOrDefault(b => b.Name == "SMTP Port");
            var fromAddress = _emailSmtpSetting.FirstOrDefault(c => c.Name == "From Address");
            var useSsl = _emailSmtpSetting.FirstOrDefault(d => d.Name == "Use SSL");
            var useDefaultCredential = _emailSmtpSetting.FirstOrDefault(e => e.Name == "Use default credentials");
            var username = _emailSmtpSetting.FirstOrDefault(f => f.Name == "SMTP Username");
            var pwd = _emailSmtpSetting.FirstOrDefault(g => g.Name == "SMTP Password");

            Dictionary<string, string> smtpSettings = new Dictionary<string, string>
            {
                { "SMTP Host", smtpHost.Detail },
                { "SMTP Port", smtpPort.Detail },
                { "From Address", fromAddress.Detail },
                { "Use SSL", useSsl.Detail },
                { "Use default credentials", useDefaultCredential.Detail },
                { "SMTP Username", username.Detail },
                { "SMTP Password", pwd.Detail }
            };

            await _userEmailer.TryToSendEmail(user, message, subject, recipientEmail, AbpSession.GetTenantId(), emailTemplate, smtpSettings);
        }
    }

The desired outcome is for the email parameters to reach the endpoint successfully. However, the actual result I am encountering is a 401 unauthorized error.

Answer №1

If you're facing an unresolved issue and haven't shared your complete controller, I'm assuming that you are using an API controller structured like the one below:

[Route("[controller]")]
[ApiController]
public class EmailComponentsController : ControllerBase
{
    [HttpPost]
    public async Task SendEmail(string recipientEmail, string subject, [FromBody] string message, string emailTemplate)
    {
       // Add your code here...
    }
}

When making a POST request, the MVC pipeline will match the method based on the HTTP verb (POST in this case), so avoid putting the method name in the URL...

This URL format is correct:

somedomain.com/EmailComponents?recipientEmail=testEmail&subject=testSubject

Avoid using this URL format:

somedomain.com/EmailComponents/sendemail?recipientEmail=testEmail&subject=testSubject

If accessed incorrectly, it should return a 404 error instead of a 401 response.

Have you considered removing authentication from your controller to troubleshoot? Try adding the [AllowAnonymous] attribute to either the class or method for testing purposes.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Discover the dynamic trio of Quartz, Unity, and the .NET framework

Can I ensure that a quartz job always uses the same instance of IJob injected by DI container Unity? I have a unique instance "monitor" of a class Monitor obtained from Unity DI, which was registered like this: container.RegisterType<IMonitor, Monitor& ...

Laravel web socket pusher malfunctioning despite the event being triggered

I've been working on integrating Laravel Websocket for socket connections in my application. Despite following all the steps outlined in the Laravel documentation, I'm encountering issues. The dashboard does not display any active connections, a ...

Utilize Buildr in C# to refine an embedded list in MongoDB

I'm facing an issue while trying to write a query using C# for my data model. The structure of my data model is as follows: public class SpamEntity:MongoEntity { public IList<MessageData> MessageData { get; set; } } public class Messag ...

Solving Circular Dependencies in React with TypeScript by using smart importing techniques

I've set up a union type in the parent component export type Students = "fresher" | "secondYear" | 'finalYear' | 'postGrad'; A circular dependency is causing issues, and the most obvious solution is to define ...

The Observable<T> generic type must be provided with one type argument

I encountered the following 3 errors while working with the Angular 2 (TypeScript) code below. Can you provide suggestions on how to resolve them? import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { NgModule, Com ...

Slate - developing a TypeScript function to filter and retrieve an object containing the highest property value

Check out this NEW RELATED QUESTION: I need to extract the largest number from a given object set. I am struggling with finding a solution. I have tried using max but I think my skills are lacking. Here is the code I have so far: @Function() pub ...

What should be the datatype of props in a TypeScript functional HOC?

My expertise lies in creating functional HOCs to seamlessly integrate queries into components, catering to both functional and class-based components. Here is the code snippet I recently developed: const LISTS_QUERY = gql` query List { list { ...

Changes in model not reflected in the view

In my Angular app (5.2.3), I have implemented a feature to display a login/logout button in the top right corner of the page. The functionality involves silently logging the user in using an external Open ID Connect provider and then displaying the user&ap ...

ag-grid angular - update group row when selection changes

After thoroughly reviewing the documentation and API references, I have not found a method to initiate a refresh on a group row when a selection change is made to its children. In my current project using ag-grid in Angular 7, I am utilizing a custom rend ...

What is the proper way to define and update a variable within a React Class Component in order to maintain a reference to a setTimeout function

Having primarily worked with React function components, my typical approach is to declare consts inside the function. However, I recently encountered a situation where I needed to declare a variable in a class component, and I experimented with three diffe ...

Error TS2339: The specified property is not found within the given type of 'IntrinsicAttributes & IntrinsicClassAttributes<FormInstance<{}, Partial<ConfigProps<{}, {}>>>> & ...'

Recently diving into the world of TypeScript and Redux, I've been tackling the SimpleForm example from redux-form. Below is the form component I'm working with: import * as React from 'react'; import {Field, reduxForm} from 'redu ...

When I refresh my Angular web application, I encounter a '404 error'

Having a two-page web service setup consisting of a Main page and a details page, I encountered an issue. When I double click on the main page data, it successfully directs me to the details page with all the relevant information displayed. However, whenev ...

Error TS2307: Module 'bluebird' not located

Currently, my focus is on developing an app using Ionic 2 and Angular 2 along with Typescript. To incorporate messaging into my app, I opted to utilize the library amqp-ts. The installation of the library through npm was successful with the following comma ...

Is there a way to go back to the previous URL in Angular 14?

For instance, suppose I have a URL www.mywebsite.com/a/b/c and I wish to redirect it to www.mywebsite.com/a/b I attempted using route.navigate(['..']) but it seems to be outdated and does not result in any action. ...

Issues with Angular Http Subscribe functionality not functioning as expected

Hello, in my Angular Component, I have the following code in one of my methods: this.http.get("http://localhost:8080/poeples") .map( resp => { resp = resp.json(); } ).subscribe( (data) => { this.poeples = data; }, err => console.log( ...

What is the best way to refresh my component following a delete operation in React?

I am currently facing an issue with using Sweetalert2 and React (tsx) where I am unsure how to refresh my item list after deleting methods. Below is the code snippet that I have for a button that implements these functions: function DeleteCard(item: DataI ...

Combining Angular 1.3.4 and Angular 2 - A comprehensive guide

Currently, I have an application built on Angular 1.3.4 and my goal is to gradually transition it to Angular 2, module by module. For instance, if there are 5 modules on my webpage, I want to move one module to Angular 2 while keeping the other modules ru ...

Can the SharePoint Graph API be accessed in Angular without requiring Azure app registration delegates and application permissions?

After creating our Angular application, we successfully implemented single sign-on using Azure app registration and MSAL library. Our goal is to access the SharePoint document graph API without requiring delegate or application level permissions in the ap ...

Issue with Firebase Functions trigger not activating

Just delving into the world of Firebase Functions for the first time using Typescript. I've written two functions: export const helloWorld = functions.https.onRequest((request, response) => { response.send("Hello from Firebase!"); const testRe ...

Outputting a JS file per component using Rollup and Typescript

Currently, I am in the process of developing a component library using React, TypeScript, and Rollup. Although bundling all components into a single output file index.js is functioning smoothly, I am facing an issue where individual components do not have ...