Sometimes, we want to send emails with JavaScript.
In this article, we’ll look at how to send emails with JavaScript.
How to send emails with JavaScript?
To send emails with JavaScript, we can create a mailto
URL and go to it.
For instance, we write
const sendMail = () => {
const link =
"mailto:me@example.com" +
"?cc=myCCaddress@example.com" +
"&subject=" +
encodeURIComponent("This is my subject") +
"&body=" +
encodeURIComponent(document.getElementById("myText").value);
window.location.href = link;
};
to define the sendMail
function that creates the link
mailto
URL.
mailto:
has the address to send the email to.
cc
has the CC email.
subject
has the subject.
body
has the email body.
We use encodeURIComponent
to encode the values so that they can be in the URL.
Then we set window.location.href
to link
to open the default mail client with the data from the URL filled as the value in the fields.
Conclusion
To send emails with JavaScript, we can create a mailto
URL and go to it.