Send email using javascript w3schools

By using PHP scripts, emails can be sent directly.

PHP mail() Function

PHP mail() function is used to send emails.

Syntax:

mail(to,subject,message,headers,parameters) 

This mail() function accepts five parameters as follows and (the last two are optional).

Parameters Details
to The recipient's email address.
subject The email's subject line.
message The actual email body where you can insert main messages.
headers Additional parameters such as "From", "Cc", "Bcc" etc.
parameters Optional parameters.

PHP Simple Email

Example:

<?php
$to = "";
$subject = "Test mail";
$message = "Hello! This is a test email message.";
$from = "";
$headers = "From:" . $from;

mail($to,$subject,$message,$headers)
?>

PHP Email Form

Example:

<?php
if(isset($_POST["SubmitBtn"])){

$to = "";
$subject = "Contact mail";
$from=$_POST["email"];
$msg=$_POST["msg"];
$headers = "From: $from";

mail($to,$subject,$msg,$headers);
echo "Email successfully sent.";
}
?>

<form id="emailForm" name="emailForm" method="post" action="" >
<table width="100%" border="0" align="center" cellpadding="4" cellspacing="1">
<tr>
  <td colspan="2"><strong>Online Contact Form</strong></td>
</tr>
<tr>
  <td>E-mail :</td>
  <td><input name="email" type="text" id="email"></td>
</tr>
<tr>
  <td>Message :</td>
  <td>
  <textarea name="msg" cols="45" rows="5" id="msg"></textarea>
  </td>
</tr>
<tr>
  <td>&nbsp;</td>
  <td><input name="SubmitBtn" type="submit" id="SubmitBtn" value="Submit"></td>
</tr>
</table>
</form>

Sending HTML Email

When you send a text message using PHP, then email content will be treated as ordinary text. HTML tags also.

You have to specify a Mime-version, content type and character set to send an HTML email.

Example:

<?php
$to = "";
$subject = "Test mail";
$message = "Hello! This is a <strong>HTML</strong> test email message.";
$from = "";
$headers = "From:" . $from\r\n;
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-type: text/html\r\n";

mail($to,$subject,$message,$headers)
?>


Send email using javascript w3schools

JavaScript is a programming language that you can use for both front-end and back-end development. When the name JavaScript is used in the context of sending emails, Node.js is the first thing that comes to mind. We even blogged about how to send emails with Node.js. In this article, we want to change the perspective from the server-side to the client-side. Let’s figure out how you can use JS to send emails from the app that has no back-end. 

Can I send emails with JS or not?

You can’t send emails using JavaScript code alone due to lack of support for server sockets. For this, you need a server-side language that talks to the SMTP server. You can use JS in conjunction with a server script that will send emails from the browser based on your requests. This is the value we’re going to introduce below.

Why you might want to send emails with JS

Traditionally, the server-side of a regular app is responsible for sending emails. You will need to set up a server using back-end technology. The client-side sends a request to the server-side, which creates an email and sends it to the SMTP server. If you’re curious about what happens with an email after that, read our blog post, SMTP relay. 

So, why would anyone be willing to go another way and send emails right from the client-side using JavaScript? Such an approach is quite useful for building contact forms or other kinds of user interaction on web apps, which allows your app to send an email without refreshing the page the user is interacting with. Besides, you don’t have to mess around with coding a server. This is a strong argument if your web app uses email sending for contact forms only. Below, you will find a few options on how to make your app send emails from the client-side. 

mailto: for sending form data 

Since you can’t send an email directly with JS, you can tell the browser to open a default mail client to do so. Technically, the mailto: method does not send email directly from the browser, but it can do the job. Check out how the following code example works:

<form action="mailto:" method="post" enctype="text/plain" >
FirstName:<input type="text" name="FirstName">
Email:<input type="text" name="Email">
<input type="submit" name="submit" value="Submit">
</form>

When you launch it in the browser, you’ll see the following:

Send email using javascript w3schools

Once the data has been submitted, the browser opens a default mail client. In our case, this is Gmail.

Send email using javascript w3schools

The mailto: method is a rather easy solution to implement but it has some specific drawbacks:

  • You can’t control the layout of the data since the data is submitted in the form sent by the browser.
  • mailto: doesn’t protect your email address from being harvested by spambots. Some time ago, this could be mitigated by constructing a link in JS. These days, more and more bots run JS and do not rely on HTML rendered by the server alone.

SmtpJS is a free library you can use for sending emails from JavaScript. All you need is an SMTP server and a few manipulations to get things done. We’ll use Mailtrap as the server because it is an actionable solution for email testing. Below is the flow you should follow:

  • Create an HTML file (for example, test.html) with the following script:
<script src="https://smtpjs.com/v3/smtp.js">
</script>
  • Create a button that will trigger the JavaScript function
<input type="button" value="Send Email" onclick="sendEmail()">
  • Write the JS function to send emails via SmtpJS.com.
function sendEmail() {
Email.send({
    Host : "smtp.mailtrap.io",
    Username : "<Mailtrap username>",
    Password : "<Mailtrap password>",
    To : '',
    From : "",
    Subject : "Test email",
    Body : "<html><h2>Header</h2><strong>Bold text</strong><br></br><em>Italic</em></html>"
}).then(
  message => alert(message)
);
}

If you have multiple recipients, you can specify an array of email addresses in the To: property.

  • Run test.html in the browser and send your email
Send email using javascript w3schools

The drawback with the code sample above is that your username and password are visible in the client-side script. This can be fixed if you utilize the encryption option provided by SmtpJS. Click the Encrypt your SMTP credentials button and fill in the required fields. 

Send email using javascript w3schools

After that, press Generate security token and use it then in your JS function instead of SMTP server settings like the following:

SecureToken : "<your generated token>"

Below you’ll find code samples for an HTML email and an email with attachment. Thanks Mailtrap, you can also see how they will look in the recipients inbox. For more about what you can do with this service, read the Mailtrap Getting Started Guide.

Code sample for sending an HTML email

<script src="https://smtpjs.com/v3/smtp.js"></script>
<input type="button" value="Send Email" onclick="sendEmail()">
<script>
function sendEmail() {
	Email.send({
    SecureToken : "<your generated token>",
    To : '',
    From : "",
    Subject : "Test Email",
    Body : "<html><h2>Header</h2><strong>Bold text</strong><br></br><em>Italic</em></html>"
    }).then(
        message => alert("mail sent successfully")
    );
}
</script>

Inspect Your Emails

Code sample for sending an email with attachments 

For sending an email with an attachment, use the Attachments property, as follows: 

<script src="https://smtpjs.com/v3/smtp.js"></script>
<input type="button" value="Send Email" onclick="sendEmail()">
<script>
function sendEmail() {
Email.send({
    SecureToken : "<your generated token>",
    To : '',
    From : "",
    Subject : "Test Email",
    Body : "<html><h2>Header</h2><strong>Bold text</strong><br></br><em>Italic</em></html>",
	Attachments : [
	{
		name : "smtp.png",
		path : "https://…/smtp.png"
	}]
	}).then(
  		message => alert(message)
	);
}
</script>

EmailJS

EmailJS.com was already featured in our blog post, Sending Emails with ReactJS. This service allows you to connect your email service, build an email template and send it from JavaScript without any server code. Let’s check out the scope.

  • Create an account and choose an email service to connect with. There are the popular transactional services options available, such as Amazon SES or Mailgun, as well as personal services like Gmail or Outlook. You can also add a custom SMTP server. That’s what we’re going to do since we use Mailtrap. 
Send email using javascript w3schools
  • Create an email template using the built-in editor. The editor provides plenty of options for content building and other useful features, such as auto-reply, reCAPTCHA verification, and more. It’s also necessary to understand the basics of coding your own HTML email template. For this, read our Guide on How to Build HTML Email. Once this is done, click Save.

One of the major benefits of EmailJS.com is that the typical email attributes are hidden. The template includes the recipient field and it cannot be overridden from JS, so you send the template you have configured previously.

  • Now you need to install EmailJS SDK. This can be done with npm:
npm install emailjs-com --save

or bower

bower install emailjs-com --save

If you need to use EmailJS on your website, paste the following code before closing tag:

<script type="text/javascript"
        src="https://cdn.jsdelivr.net/npm//dist/email.min.js">
</script>
<script type="text/javascript">
   (function(){
      emailjs.init("YOUR_USER_ID"); //use your USER ID
   })();
</script>
  • The actual email sending can be carried out via two methods: emailjs.send or emailjs.sendForm. Here are the code examples for both of them:

emailjs.send

var templateParams = {
    name: 'James',
    notes: 'Check this out!'
};

emailjs.send('YOUR_SERVICE_ID', 'YOUR_TEMPLATE_ID', templateParams) //use your Service ID and Template ID
    .then(function(response) {
       console.log('SUCCESS!', response.status, response.text);
    }, function(error) {
       console.log('FAILED...', error);
    });

emailjs.sendForm

var templateParams = {
    name: 'James',
    notes: 'Check this out!'
};

emailjs.sendForm('YOUR_SERVICE_ID', 'YOUR_TEMPLATE_ID', templateParams) //use your Service ID and Template ID
    .then(function(response) {
       console.log('SUCCESS!', response.status, response.text);
    }, function(error) {
       console.log('FAILED...', error);
    });

Code sample for sending emails 

Let’s check whether EmailJS.com works by sending an email straight from the browser. We’ve set up an email service, Mailtrap, and built a simple template. Now, we need to create an HTML file with the following code:

<script type="text/javascript"
        src="https://cdn.jsdelivr.net/npm//dist/email.min.js">
</script>
<script type="text/javascript">
   (function(){
      emailjs.init("<USER-ID>"); //Insert your User ID
   })();
</script>
<script>
	var templateParams = {
    name: 'Sender',
    notes: 'Test email'
};

emailjs.send('<email-service-ID>', '<email-template-ID>', templateParams) //Insert your email service ID and email template ID
    .then(function(response) {
       console.log('SUCCESS!', response.status, response.text);
    }, function(error) {
       console.log('FAILED...', error);
    });
</script>

Run it in the browser and check out the Mailtrap Demo Inbox. It works!

But there’s a much easier and quicker way to send emails and avoid using browsers altogether. Mailtrap Email Delivery allows you to quickly verify your domain and use our API or SMTP to send emails, after testing them.  

Pricing

EmailJS offers a free subscription plan that allows you to send up to 200 emails per month using only two templates. In addition, you’ll have a limited list of contacts and email size (up to 50Kb). Higher quotas are available for paid subscriptions: Personal ($5/month), Professional ($15/month), and Business ($50/month). 

To wrap up

Although sending emails is a server-side thing, you can refrain from dealing with server-side coding. SmtpJS and EmailJS are two actionable solutions to streamline your front-end and make it able to send emails. EmailJS is better because it hides typical email attributes and you are able to send whatever templates you have configured before. The mailto: method is different but it can also be useful in some cases. If you, however, have changed your mind and are willing to set up back-end for your app, check out one of our dedicated blog posts:

  • How to send emails with Python
  • How to send emails with Ruby
  • How to send emails with PHP 
  • How to send emails with ASP.NET C#

Can I send an email using JavaScript?

Can I send emails with JS or not? You can't send emails using JavaScript code alone due to lack of support for server sockets. For this, you need a server-side language that talks to the SMTP server. You can use JS in conjunction with a server script that will send emails from the browser based on your requests.

How do you use JavaScript in email?

3 Answers.
First,Go to this site [https://www.emailjs.com/] and create free account..
below 'Connect your email service' button click and configure. ... .
Then 'Create email template' button click and configure. ... .
click on 'Send email from JavaScript' button..

How do you send an email in HTML code?

How to make an email link in HTML.
Open your HTML file and choose where to insert your email link..
Type in the anchor tag "a href=" after the "<" symbol to show a link in your HTML code..
Include the "mailto:" tag after the "=" to send the link to an email address..

How do I use Smtpjs?

How to Send Emails From Javascript?.
Introduction. ... .
Create below two files in a folder: ... .
Download the smtp.js or include a script tag to https://smtpjs.com/v3/smtp.js. ... .
Next step is to include a script file which will have the SMTP details and a mail template..