To Send Emails in JavaScript Using SMTP (Simple Mail Transfer Protocol), we will use JavaScript SMTP CDN and Gmail app password as credentials.
Here are the given major things we will use to send an email in JavaScript using SMTP,
- SMTP JS CDN library
- Google App Password
Here you can check how we can create a google app password https://codingtasks.net/send-mail-from-localhost-in-php-using-xampp/#Create_an_APP_password_to_setup_Gmail_SMTP.
After getting, both things we can start code to do JavaScript and send an email on button click.
Steps to create JavaScript send an email on button click,
- Creating a simple form with the sender, receiver, and message fields.
- Adding SMTP CDN script
- Creating an email send function
- On send function, we will set the host, username, and previously created app password.
- After that from, to, subject, and text content.
Complete example to send an email in JavaScript using SMTP
Creating a simple form,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Send Email</title> </head> <body> <form method="post" name="Form"> <p><input type="Email" id="sender" placeholder="sender@gmail.com"></p> <p><input type="Email" id="reciever" placeholder="Reciever@gmail.com"></p> <p><input type="text" id="content" placeholder="Enter Email Content" id="Message"></p> <p><input type="button" value="Send Email" onclick="sendMail()"></p> </form> |
Adding SMTP CDN,
1 |
<script src="http://smtpjs.com/v3/smtp.js"></script> |
Now, we will add an SMTP email send function to send an email,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
<script type="text/javascript"> getData = (elemId) => { //getting values from input fields return document.getElementById(elemId).value; } sendMail = () => { var sender = getData("sender"); var receiver = getData("reciever"); var content = getData("content"); //Sending email Email.send({ Host: "smtp.gmail.com", Username: "youremail@gmail.com", Password:"anandksdjdsihun", To: receiver, From: sender, Subject: "Check Email Sending", Body: content, }).then(function (message) { alert("Email sent successfully") }); } </script> </body> </html> |
Note: You can merge complete codes by copying and pasting them one by one.
Above is the complete code to send emails in JavaScript Using SMTP with a button click.
I hope you will understand the complete code. To know more you can check here SmtpJS.com – Send Email from JavaScript
Happy Coding..!
[…] Send Emails in JavaScript Using SMTP with Example February 23, 2022 […]
[…] Send Emails in JavaScript Using SMTP with Example February 23, 2022 […]
hey it doesn’t owrk for me …
can u ontact me by email ?
[…] Send Emails in JavaScript Using SMTP with Example […]