How do I create an email service in Angular 7 that contains a method for sending out emails?
For example:
// email.service.ts
import { Injectable } from ‘@angular/core’;
@Injectable()
export class EmailService {
constructor() { }
// method to fetch data from server
public sendEmail(): void {
// logic to send email
...
}
}
I'm new to developing with Angular so any examples, use cases, and/or code snippets are greatly appreciated.
You could use some BaaS (Backend as a service) provider, like Formspree. It's pretty simple to use and enables you to send emails without have to write or setup a backend. All you have to do is post an Http request from your angular application and this service takes care of the rest.
Then you'll get an unique endpoint for this newly create form wich you can use to send (post) emails to from your angular application. The endpoint will look something like this : https://formspree.io/asdlf7asdf
Here is some example code using Template driven forms:
<form (ngSubmit)="onSubmit(contactForm)" #contactForm="ngForm">
<input type="text" placeholder="Name" name="name" ngModel required #name="ngModel">
<input type="text" placeholder="Email" email name="email" ngModel required #email="ngModel">
<textarea placeholder="Messages" name="messages" ngModel required #messages="ngModel"></textarea>
<input type="submit" value="Send">
</form>
onSubmit(contactForm: NgForm) {
if (contactForm.valid) {
const email = contactForm.value;
const headers = new HttpHeaders({ 'Content-Type': 'application/json' });
this.http.post('https://formspree.io/asdlf7asdf',
{ name: email.name, replyto: email.email, message: email.messages },
{ 'headers': headers }).subscribe(
response => {
console.log(response);
}
);
}
}
You can do much more with this (or other) services but this would be the basic gist of it.
Angular working at client side and for sending email you need a server, so I think it is impossible for now to send email using only angular you need to used server side application for sending email.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With