18910140161

通过JavaScript发送邮件,单击html提交按钮

顺晟科技

2021-08-04 11:23:14

173

当在html网页上单击提交按钮时,我正试图使用JavaScript发送邮件。下面是我的HTML代码...

<!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(); return false">Send</button>
</body>
</html>

以下是我在javascript中使用的senMail函数,用于处理post->

 function myFunction(){
  var link="mailto:amarhutiappa@gmail.com"
  + "?cc=mrinal.annand@gmail.com"
  + "&subject=" + encodeURIComponent("This is my subject")
  + "&body="+encodeURIComponent(document.getElementsById('myText')).value
;

window.location.href = link;
}

我不明白我哪里做错了!请有人建议正确的方法


顺晟科技:

您的代码中有一些错误,下面是修复的代码... 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>

首先,您没有在JavaScript代码中定义函数sendMail(),而是定义了myFunction()。其次,更好将邮件地址、抄送收件人、主题和正文指定为变量,因为它们可以是动态的,也可以很容易地更改硬编码的值。接下来,您可以使用ES6模板文本连接变量,以便于阅读代码。

如果您想了解HTMLmailto的用法,请参阅本文

  • TAG:
相关文章
我们已经准备好了,你呢?
2024我们与您携手共赢,为您的企业形象保驾护航