简体   繁体   English

如何在不打开邮件客户端的情况下使用 JavaScript 发送电子邮件?

[英]How do I send email with JavaScript without opening the mail client?

I'm writing a HTML page with a registration button that should just silently send an email without opening the local mail client.我正在编写一个带有注册按钮的 HTML 页面,该页面应该在不打开本地邮件客户端的情况下静默发送电子邮件。 Here is my HTML:这是我的 HTML:

<form method="post" action="">
    <input type="text" id="email_address" name="name" placeholder="Enter your email address..." required>
    <button onclick="sendMail(); return false">Send Email</button>
</form>

... and here is my JavaScript code: ...这是我的 JavaScript 代码:

<script type="text/javascript">
  function sendMail() {
    var link = 'mailto:hello@domain.com?subject=Message from '
             +document.getElementById('email_address').value
             +'&body='+document.getElementById('email_address').value;
    window.location.href = link;
}
</script>

The code above works... but it opens the local email client.上面的代码有效......但它打开了本地电子邮件客户端。 If I remove the return statement in the onclick attribute like this:如果我删除onclick属性中的return语句,如下所示:

<form method="post" action="">
    <input type="text" id="email_address" name="name" placeholder="Enter your email address..." required>
    <button onclick="sendMail()">Send Email</button>
</form>

... then the email is not sent at all. ...然后根本没有发送电子邮件。 Am I missing something?我错过了什么吗?

Any help would be reeeally appreciated :-)任何帮助将不胜感激:-)

You cannot cause the user's browser to send email silently.您不能让用户的浏览器静默发送电子邮件。 That would be a horrible security problem as any website could use their system as a spam relay and/or harvest their email address.这将是一个可怕的安全问题,因为任何网站都可以将其系统用作垃圾邮件中继和/或获取其电子邮件地址。

You need to make an HTTP request to a server side process (written in the language of your choice) which sends the mail from your server.您需要向从您的服务器发送邮件的服务器端进程(以您选择的语言编写)发出 HTTP 请求。

You need a server-side support to achieve this.您需要服务器端支持来实现这一点。 Basically your form should be posted (AJAX is fine as well) to the server and that server should connect via SMTP to some mail provider and send that e-mail.基本上,您的表单应该发布(AJAX 也可以)到服务器,并且该服务器应该通过 SMTP 连接到某个邮件提供商并发送该电子邮件。

Even if it was possible to send e-mails directly using JavaScript (that is from users computer), the user would still have to connect to some SMTP server (like gmail.com), provide SMTP credentials, etc. This is normally handled on the server-side (in your application), which knows these credentials.即使可以直接使用 JavaScript(即来自用户计算机)发送电子邮件,用户仍然必须连接到某个 SMTP 服务器(如 gmail.com),提供 SMTP 凭据等。这通常在服务器端(在您的应用程序中),它知道这些凭据。

Directly From Client直接来自客户


Send an email using only JavaScript仅使用 JavaScript 发送电子邮件

in short: 
1. register for Mandrill to get an API key
2. load jQuery
3. use $.ajax to send an email

Like this -像这样 -

function sendMail() {
    $.ajax({
      type: 'POST',
      url: 'https://mandrillapp.com/api/1.0/messages/send.json',
      data: {
        'key': 'YOUR API KEY HERE',
        'message': {
          'from_email': 'YOUR@EMAIL.HERE',
          'to': [
              {
                'email': 'RECIPIENT@EMAIL.HERE',
                'name': 'RECIPIENT NAME (OPTIONAL)',
                'type': 'to'
              }
            ],
          'autotext': 'true',
          'subject': 'YOUR SUBJECT HERE!',
          'html': 'YOUR EMAIL CONTENT HERE! YOU CAN USE HTML!'
        }
      }
     }).done(function(response) {
       console.log(response); // if you're into that sorta thing
     });
}

https://medium.com/design-startups/b53319616782 https://medium.com/design-startups/b53319616782

Note: Keep in mind that your API key is visible to anyone, so any malicious user may use your key to send out emails that can eat up your quota.注意:请记住,任何人都可以看到您的 API 密钥,因此任何恶意用户都可能使用您的密钥发送电子邮件,这可能会耗尽您的配额。


Indirect via Your Server - secure通过您的服务器间接- 安全


To overcome the above vulnerability, you can modify your own server to send the email after session based authentication.为了克服上述漏洞,您可以修改自己的服务器以在基于会话的身份验证后发送电子邮件。

node.js - https://www.npmjs.org/package/node-mandrill node.js - https://www.npmjs.org/package/node-mandrill

var mandrill = require('node-mandrill')('<your API Key>'); 

function sendEmail ( _name, _email, _subject, _message) {
    mandrill('/messages/send', {
        message: {
            to: [{email: _email , name: _name}],
            from_email: 'noreply@yourdomain.com',
            subject: _subject,
            text: _message
        }
    }, function(error, response){
        if (error) console.log( error );
        else console.log(response);
    });
}

// define your own email api which points to your server.

app.post( '/api/sendemail/', function(req, res){

    var _name = req.body.name;
    var _email = req.body.email;
    var _subject = req.body.subject;
    var _messsage = req.body.message;

    //implement your spam protection or checks. 

    sendEmail ( _name, _email, _subject, _message );

});

and then use use $.ajax on client to call your email API.然后在客户端使用 $.ajax 调用您的电子邮件 API。

您不能仅使用客户端脚本来执行此操作...您可以对某些将发送电子邮件的服务器端代码进行 AJAX 调用...

我想你可以使用smtpjs.com

There needs to be some type of backend framework to send the email.需要某种类型的后端框架来发送电子邮件。 This can be done via PHP/ASP.NET, or with the local mail client.这可以通过 PHP/ASP.NET 或本地邮件客户端来完成。 If you want the user to see nothing, the best way is to tap into those by an AJAX call to a separate send_email file.如果您不希望用户看到任何内容,最好的方法是通过 AJAX 调用对单独的 send_email 文件进行访问。

You need to do it directly on a server.您需要直接在服务器上执行此操作。 But a better way is using PHP.但更好的方法是使用 PHP。 I have heard that PHP has a special code that can send e-mail directly without opening the mail client.听说PHP有一个特殊的代码,可以不用打开邮件客户端直接发送邮件。

Well, PHP can do this easily.嗯,PHP 可以轻松做到这一点。

It can be done with the PHP mail() function.它可以通过 PHP mail()函数来完成。 Here's what a simple function would look like:下面是一个简单的函数的样子:

<?php     
$to_email = 'name@company.com';
$subject = 'Testing PHP Mail';
$message = 'This mail is sent using the PHP mail function';
$headers = 'From: noreply@company.com';
mail($to_email,$subject,$message,$headers);
?>

This will send a background e-mail to the recipient specified in the $to_email .这将向$to_email指定的收件人发送后台电子邮件。

The above example uses hard coded values in the source code for the email address and other details for simplicity.为简单起见,上面的示例在源代码中使用硬编码值作为电子邮件地址和其他详细信息。

Let's assume you have to create a contact us form for users fill in the details and then submit.假设您必须创建一个与我们联系的表单,供用户填写详细信息然后提交。

  1. Users can accidently or intentional inject code in the headers which can result in sending spam mail用户可能会无意或有意地在标头中注入代码,从而导致发送垃圾邮件
  2. To protect your system from such attacks, you can create a custom function that sanitizes and validates the values before the mail is sent.为了保护您的系统免受此类攻击,您可以创建一个自定义函数,在发送邮件之前清理和验证这些值。

Let's create a custom function that validates and sanitizes the email address using the filter_var() built in function.让我们创建一个使用filter_var()内置函数验证和清理电子邮件地址的自定义函数。

Here's an example code:这是一个示例代码:

<?php 
function sanitize_my_email($field) {
    $field = filter_var($field, FILTER_SANITIZE_EMAIL);
    if (filter_var($field, FILTER_VALIDATE_EMAIL)) {
        return true;
    } else {
        return false;
    }
}
$to_email = 'name@company.com';
$subject = 'Testing PHP Mail';
$message = 'This mail is sent using the PHP mail ';
$headers = 'From: noreply@company.com';
//check if the email address is invalid $secure_check
$secure_check = sanitize_my_email($to_email);
if ($secure_check == false) {
    echo "Invalid input";
} else { //send email 
    mail($to_email, $subject, $message, $headers);
    echo "This email is sent using PHP Mail";
}
?>

We will now let this be a separate PHP file, for example sendmail.php .我们现在将其设为一个单独的 PHP 文件,例如sendmail.php

Then, will use this file on form submission, using the action attribute of the form, like:然后,将在表单提交时使用此文件,使用表单的action属性,例如:

<form action="sendmail.php" method="post">
   <input type="text" value="Your Name: ">
   <input type="password" value="Set Up A Passworrd">
   <input type="submit" value="Signup">
   <input type="reset" value="Reset Form">
</form>

Hope I could help希望我能帮上忙

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用Javascript发送电子邮件? - How do I send an email using Javascript? 是否可以仅使用Javascript发送电子邮件而不必单击电子邮件客户端上的“发送”按钮? - Can I Send an Email using ONLY Javascript Without Having to Click The Send Button on the Email Client? 如何启动 eMail 客户端,然后使用 Javascript 进行页面重定向? - How can I launch the eMail client, and then do a page redirect with Javascript? 如何通过HTML和JavaScript发送电子邮件? - How do I send email through HTML and JavaScript? 如何使用JavaScript通过Rails 3 Action Mailer发送电子邮件? - How do I use JavaScript to send an email with the Rails 3 Action Mailer? 我无法通过电子邮件发送电子邮件 - I can not send an email to the mail 如何将带有Node的视频发送到客户端JavaScript blob然后显示它? - How do I send video with Node to a client JavaScript blob and then display it? 如何使用 JavaScript 将 HTML 表单数据通过电子邮件发送到电子邮件 ID,而不使用服务器端语言,而不使用电子邮件客户端安全? - How to send HTML form data by email to an email ID by using JavaScript, without using server-side language, without using email client securely? 如何在不打开本机应用程序的情况下使用phonegap发送短信? - How do i send a SMS using phonegap without opening the native app? 如何在不打开Javascript窗口的情况下发送HTTP请求? - How to send HTTP requests without opening up windows in Javascript?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM