Edit - Send an email directly via JavaScript
If you are looking to send an email without using html mailto:
there is a library called smtpJS. View a simplified tutorial here.
BUT I WOULD NOT SUGGEST TO USE YOUR PERSONAL EMAIL HERE
In your case you can use it like below
const sendMail = (e) => {
e.preventDefault()
const message = encodeURIComponent(document.getElementById('message').value)
Email.send({
Host : "smtp.yourisp.com",
Username : "username",
Password : "password",
To : 'them@website.com',
From : "you@isp.com",
Subject : encodeURIComponent("This is my subject"),
Body : message
}).then(
message => alert(message)
).catch( err => {
alert(err)
});
}
<!DOCTYPE html>
<html lang="en">
<body>
<form method="post" onsubmit="sendMail(event)">
<textarea name="message" id="message">Sample Text</textarea>
<button type="submit">Send Email</button>
</form>
<script src="https://smtpjs.com/v3/smtp.js"></script>
</body>
</html>
You can setup your configuration as per your credentials. If you are using Gmail you can use the credentials mentioned in this article
Disclaimer
I did not test it out completely since I was reluctant to use my personal mail address and I do not have a mail address for production. Please do further research and edit this answer post if necessary
Old Answer
There were some errors in your code and here is the fixed code...
const sendMail = () => {
const mailAdress = "someone@example.com"
const ccRecipients = "mrinal.annand@gmail.com"
const subject = encodeURIComponent("This is my subject")
const body = encodeURIComponent(document.getElementById('myText').value)
const link= `mailto:${mailAdress}?cc=${ccRecipients}&subject=${subject}&body=${body}`
window.location.href = link;
}
<!DOCTYPE html>
<html>
<style>
.heading{
justify-content: center;
text-align: center;
}
</style>
<body>
<h2 class="heading">Send e-mail to someone@example.com:</h2>
<textarea name="myText" id="myText">this is a mail</textarea>
<button onclick="sendMail()">Send</button>
</body>
</html>
First of all you haven't defined the function sendMail()
in your JavaScript code and instead defined myFunction()
.
Second it's better to assign the mail address, cc recipients, subject and body as variables since they can be made dynamic or to easily change the hardcoded values. Next you can concatenate the variables using ES6 Template Literals to have in ease in reading and writing the code.
Thirdly, the below code is incorrect.
encodeURIComponent(document.getElementsById('myText')).value
You should pass the value of text area to the encodeURIComponent()
function. For that first you must get the value in text area by document.getElementsById('myText').value
and pass that value into encodeURIComponent()
. The corrected code will look like this
encodeURIComponent(document.getElementById('myText').value)
Also if you want to understand the use of HTML mailto
, refer this article