Guides
Last Updated Aug 03, 2023

Send Email From Angular

Elizabeth (Lizzie) Shipton

Table of Contents:

Get your free
API
key now
4.8 from 1,863 votes
See why the best developers build on Abstract
START FOR FREE
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
No credit card required
Get your free
Email Verification API
key now
4.8 from 1,863 votes
See why the best developers build on Abstract
START FOR FREE
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
No credit card required

Being able to send emails from the client is a very useful thing. All marketing websites need a contact form to allow potential new customers to send emails to you, and most websites need the ability to allow users to submit technical requests and bug reports.

Unfortunately, sending emails from the front end is a bit tricky. You can't simply send a regular HTTP request like you do when requesting and sending data to your backend. Email communication protocol requires additional security, and not adhering to those security rules could get you blacklisted as a spammer.

In this article, we'll look at how to send emails securely from an Angular app using a third-party SMTP server service.

Let’s send your first free
API
Email Verification API
call
See why the best developers build on Abstract
Get your free api

Get Started With an Angular App

The first thing we'll do is spin up a basic Angular app using the Angular CLI. This tutorial won't go in-depth into how to configure your Angular application, or how to work with Angular. There is more information about how to do this in the Angular docs.

Spin Up A New Angular Application

Use the CLI to create a new Angular application. The CLI will guide you through the setup process and will take a minute to install dependencies.



$ ng new angular-email-app

Once the app is created, cd into the root folder and start up the server.



$ cd angular-email-app
$ ng serve

By default, the app runs on port 4200, so head to https://localhost:4200 to see it in action.

Use Reactive Form

Angular provides a handy module for working with forms called ReactiveFormsModule. To use it, import it into your NgModule imports array from the /forms module.



import { ReactiveFormsModule } from '@angular/forms';  
@NgModule({   
imports: [ 
ReactiveFormsModule
], 
}) 
export class AppModule { }

Now, create a form component. This is where all the display logic for your form will live.



ng g c email-form

Import the FormBuilder class and inject it into the constructor:



import { FormBuilder} from '@angular/forms';
...
constructor(private builder: FormBuilder) { }

Use FormBuilder to generate all the display logic for your form. FormBuilder can even handle some basic email validation for you.



export class EmailFormComponent implements OnInit {
FormData: FormGroup;
constructor(private builder: FormBuilder) { 
ngOnInit() {
this.FormData = this.builder.group({
EmailAddress: new FormControl('', [Validators.compose([Validators.required, Validators.email])]),
Body: new FormControl('', [Validators.required])
})
}
}

As you can see, we're making the email address field required and letting the FormBuilder know that it should expect an email address in that input. If the syntax for the address is incorrect, the form will render an error.

Make the HTML Template

To render the actual form, we need some HTML. Paste the following code into the email-form.component.html file:



<div>
<h2>Angular Email Form</h2>
<div>
<div>
<form [formGroup]="FormData" (ngSubmit)="onSubmit(FormData.value)"><div>
<label for="EmailAddress">Email</label>
<input type="email" name="EmailAddress" placeholder="Enter email" formControlName="Email">
</div>
<div>
<label for="body">Body</label>
<textarea formControlName="Body" name="Body">
</textarea>
</div>
<button type="submit" [disabled]="!FormData.valid">Submit</button>
</form>
</div>
</div>
</div>

The formControlName, and name attributes tell Angular that these HTML elements should be hooked up to the FormControl component you just built.

Create an Email Service

The actual logic of sending emails will be handled by a service component. Angular uses the word service to refer to any module that handles data level logic and behind-the-scenes stuff like making HTTP requests and processing data.

Generate the email service file using the following command:



ng generate service email

Into that file, import the HttpClientModule and add it to the providers array.



import { HttpClientModule } from '@angular/common/http';
imports: [
HttpClientModule
],

...

providers: [
EmailService
],


Now, create the function that will send the email request to our third-party service.



@Injectable({
  providedIn: 'root'
})

export class EmailService {
  private url = ""
  constructor(private: http: HttpClient)

    SendEmail(input: any) {
	return this.http.post(this.url, input, response).pipe(
		map(
		  (response) => {
		      if (response) {
			return response
		      }
		  },
		  (error) => {
		      if (error) {
			return error
		      }
		   }
		)
	    )
    }
}


We've left the url variable blank for now. That will be filled in once we set up our Mailthis alias and receive a URL to post our request to.

Send Emails from an Angular App Using MailThis

The easiest way to send client-side emails is to use a third-party email service library like Mailthis. Mailthis allows you to set up a URL that redirects incoming email requests to an email address of your choosing. It's very easy to set up.

Create an Alias

In order to use Mailto, you'll need to create an alias. Head over to the website to sign up and create one. It's free.

Once you've created your alias, you'll receive an email with a confirmation link. Just click the link to confirm your alias and you're done.

Mailthis will create a unique URL that you can send a simple POST request to with the information you want to send in your email.

Add the URL you received from Mailthis to the url variable in your service.

Submit the Email

Finally, in our email-form.component.ts file, create a submitEmail function that sends our request to Mailthis.



constructor(private builder: FormBuilder, private contact: EmailService) { }
onSubmit(FormData) {
    this.contact.PostMessage(FormData)
      .subscribe(response => {
        location.href = 'https://mailthis.to/confirm'
      }, error => {
      console.warn(error.responseText)
      console.log({ error })
    })
}

That's it! We've successfully set up a client-side email API using Mailthis and Angular.

Conclusion

It's a bit trickier to send emails from the front end than it is to send regular HTTP requests. Email requires a special set of security protocols to prevent spam and bad actors from getting into people's mailboxes. Fortunately, there are tons of free services out there like Mailthis that can help you send emails from the front end.

FAQs

Can we send emails using Angular?

It is possible to send emails from Angular without writing any server-side code, using a free service like Mailthis, a free email API, or smtpJS, a client-side Javascript library. You will need to sign up with the service or download the library in order to include it in your application. Follow the documentation on the company's website for complete instructions on how to get started.

How to send emails without a backend in Angular?

Sending emails without writing your own backend is possible in Angular if you use a third-party SMTP service. These platforms act as a middleman between your application and your email client, performing all the necessary SMTP checks and following proper protocol for sending emails. It is possible to write your own Node server that will do this, but it can be complicated and difficult to scale.

How do I send a front-end email?

The mailto link is the easiest way to send an email from a front-end Javascript app, however it is not recommended. To use the mailto link, put the email address you're sending to after mailto: as part of the string. When the user clicks on the anchor tag, mailto opens the user's preferred email client and populates it with the email address.

A better way to send front-end email is to use a platform like SMTPJS or Mailthis.

4.9/5 stars (12 votes)

Elizabeth (Lizzie) Shipton
Lizzie Shipton is an adept Full Stack Developer, skilled in JavaScript, React, Node.js, and GraphQL, with a talent for creating scalable, seamless web applications. Her expertise spans both frontend and backend development, ensuring innovative and efficient solutions.
Get your free
Email Verification API
API
key now
Validate & verify emails instantly using Abstract's API.
get started for free

Related Articles

Get your free
API
Email Verification API
key now
4.8 from 1,863 votes
See why the best developers build on Abstract
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
No credit card required