简体   繁体   English

使用 Javascript 发送电子邮件

[英]Sending emails with Javascript

This is a little confusing to explain, so bear with me here...解释起来有点令人困惑,所以请耐心等待......

I want to set up a system where a user can send templated emails via my website, except it's not actually sent using my server - it instead just opens up their own local mail client with an email ready to go.我想建立一个系统,让用户可以通过我的网站发送模板化的电子邮件,除非它实际上不是使用我的服务器发送的 - 它只是打开他们自己的本地邮件客户端,并准备好发送电子邮件。 The application would fill out the body of the email with predefined variables, to save the user having to type it themselves.该应用程序将使用预定义的变量填写电子邮件的正文,以节省用户必须自己输入的情况。 They can then edit the message as desired, should it not exactly suit their purposes.然后他们可以根据需要编辑消息,如果它不完全适合他们的目的。

There's a number of reasons I want it to go via the user's local mail client, so getting the server to send the email is not an option: it has to be 100% client-side.我希望它通过用户的本地邮件客户端发送的原因有很多,因此让服务器发送电子邮件不是一种选择:它必须是 100% 的客户端。

I already have a mostly-working solution running, and I'll post the details of that as an answer, I'm wondering if there's any better way?我已经有一个主要工作的解决方案正在运行,我会发布它的详细信息作为答案,我想知道是否有更好的方法?

The way I'm doing it now is basically like this:我现在的做法基本上是这样的:

The HTML: HTML:

<textarea id="myText">
    Lorem ipsum...
</textarea>
<button onclick="sendMail(); return false">Send</button>

The Javascript: Javascript:

function sendMail() {
    var 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;
}

This, surprisingly, works rather well.令人惊讶的是,这很有效。 The only problem is that if the body is particularly long (somewhere over 2000 characters), then it just opens a new email but there's no information in it.唯一的问题是,如果正文特别长(超过 2000 个字符),那么它只会打开一封新电子邮件,但其中没有任何信息。 I suspect that it'd be to do with the maximum length of the URL being exceeded.我怀疑这与超出 URL 的最大长度有关。

Here's the way doing it using jQuery and an "element" to click on :这是使用 jQuery 和“元素”单击的方法:

$('#element').click(function(){
    $(location).attr('href', 'mailto:?subject='
                             + encodeURIComponent("This is my subject")
                             + "&body=" 
                             + encodeURIComponent("This is my body")
    );
});

Then, you can get your contents either by feeding it from input fields (ie. using $('#input1').val() or by a server side script with $.get('...') . Have fun然后,您可以通过从输入字段中获取内容(即使用$('#input1').val()或使用$.get('...')的服务器端脚本来获取内容。玩得开心

你不需要任何 javascript,你只需要你的 href 像这样编码:

<a href="mailto:me@me.com">email me here!</a>

You can use this free service: https://www.smtpjs.com您可以使用这项免费服务: https : //www.smtpjs.com

  1. Include the script:包括脚本:

<script src="https://smtpjs.com/v2/smtp.js"></script>

  1. Send an email using:使用以下方式发送电子邮件:
Email.send(
  "from@you.com",
  "to@them.com",
  "This is a subject",
  "this is the body",
  "smtp.yourisp.com",
  "username",
  "password"
);

What about having a live validation on the textbox, and once it goes over 2000 (or whatever the maximum threshold is) then display 'This email is too long to be completed in the browser, please <span class="launchEmailClientLink">launch what you have in your email client</span> '对文本框进行实时验证怎么样,一旦超过 2000(或任何最大阈值)然后显示“这封电子邮件太长而无法在浏览器中完成,请<span class="launchEmailClientLink">launch what you have in your email client</span> '

To which I'd have我有

.launchEmailClientLink {
cursor: pointer;
color: #00F;
}

and jQuery this into your onDomReady和 jQuery 到你的 onDomReady

$('.launchEmailClientLink').bind('click',sendMail);

If this is just going to open up the user's client to send the email, why not let them compose it there as well.如果这只是为了打开用户的客户端来发送电子邮件,为什么不让他们也在那里编写它。 You lose the ability to track what they are sending, but if that's not important, then just collect the addresses and subject and pop up the client to let the user fill in the body.您无法跟踪他们发送的内容,但如果这不重要,那么只需收集地址和主题并弹出客户端让用户填写正文。

The problem with the very idea is that the user has to have an email client, which is not the case if he rely on webmails, which is the case for many users.这个想法的问题在于用户必须有一个电子邮件客户端,如果他依赖网络邮件,情况就不是这样,许多用户都是这种情况。 (at least there was no turn-around to redirect to this webmail when I investigated the issue a dozen years ago). (至少在我十几年前调查这个问题时没有重定向到这个网络邮件)。

That's why the normal solution is to rely on php mail() for sending emails (server-side, then).这就是为什么通常的解决方案是依靠 php mail() 来发送电子邮件(然后是服务器端)。

But if nowadays "email client" is always set, automatically, potentially to a webmail client, I'll be happy to know.但是,如果现在“电子邮件客户端”总是自动设置,可能是网络邮件客户端,我会很高兴知道。

Send request to mandrillapp.com :mandrillapp.com发送请求:

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 && xhttp.status == 200) {
        console.log(xhttp.responseText);
    }
}
xhttp.open('GET', 'https://mandrillapp.com/api/1.0/messages/send.json?message[from_email]=mail@7995.by&message[to][0][email]=zdanevich.vitaly@yaa.ru&message[subject]=Заявка%20с%207995.by&message[html]=xxxxxx&key=oxddROOvCpKCp6InvVDqiGw', true);
xhttp.send();

You can add the following to the <head> of your HTML file:您可以将以下内容添加到 HTML 文件的<head>中:

<script src="https://smtpjs.com/v3/smtp.js"></script>

<script type="text/javascript">
    function sendEmail() {
        Email.send({
            SecureToken: "security token of your smtp",
            To: "someone@gmail.com",
            From: "someone@gmail.com",
            Subject: "Subject...",
            Body: document.getElementById('text').value
        }).then( 
            message => alert("mail sent successfully")
        );
    }
</script>

and below is the HMTL part:以下是 HMTL 部分:

<textarea id="text">write text here...</textarea>
<input type="button" value="Send Email" onclick="sendEmail()">

So the sendEmail() function gets the inputs using:所以 sendEmail() 函数使用以下方法获取输入:

document.getElementById('id_of_the_element').value document.getElementById('id_of_the_element').value

For example, you can add another HTML element such as the subject (with id="subject"):例如,您可以添加另一个 HTML 元素,例如主题(带有 id="subject"):

<textarea id="subject">write text here...</textarea>

and get its value in the sendEmail() function:并在 sendEmail() 函数中获取它的值:

Subject: document.getElementById('subject').value主题:document.getElementById('subject').value

And you are done!你已经完成了!

Note: If you do not have a SMTP server you can create one for free here .注意:如果您没有 SMTP 服务器,您可以在这里免费创建一个。 And then encrypt your SMTP credentials here (the SecureToken attribute in sendEmail() corresponds to the encrypted credentials generated there).然后在此处加密您的 SMTP 凭据(sendEmail() 中的 SecureToken 属性对应于在此处生成的加密凭据)。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM