ChatGPT解决这个技术问题 Extra ChatGPT

How to send an email from JavaScript

I want my website to have the ability to send an email without refreshing the page. So I want to use Javascript.

<form action="javascript:sendMail();" name="pmForm" id="pmForm" method="post">
Enter Friend's Email:
<input name="pmSubject" id="pmSubject" type="text" maxlength="64" style="width:98%;" />
<input name="pmSubmit" type="submit" value="Invite" />

Here is how I want to call the function, but I'm not sure what to put into the javascript function. From the research I've done I found an example that uses the mailto method, but my understanding is that doesn't actually send directly from the site.

So my question is where can I find what to put inside the JavaScript function to send an email directly from the website.

function sendMail() {
    /* ...code here...    */
}
Use server side language to actually send the email, and AJAX to have the look and feel you desire.
This might be a bit late, but this might help you: stackoverflow.com/questions/271171/…
Gmail users can have it, see developers.google.com/gmail/api
As mentioned below, you may also want to take a look at EmailJS, which allows sending email using pre-built templates directly from Javascript, and also supports dynamic parameters, attachments, captcha, REST API and more. We also offer a free tier to get started [disclosure - I'm one of the creators]
Note if you use the accepted answer, the email will come from the user’s account. To send an email from your personal or business account, the right way is to use javascript to send email through your own server or a third-party service such as Byteline. More details in this answer down below.

J
Jacob

You can't send an email directly with javascript.

You can, however, open the user's mail client:

window.open('mailto:test@example.com');

There are also some parameters to pre-fill the subject and the body:

window.open('mailto:test@example.com?subject=subject&body=body');

Another solution would be to do an ajax call to your server, so that the server sends the email. Be careful not to allow anyone to send any email through your server.


If the program which open the page have already e-mail client features.. (like Opera 12.50) then, it open the link as a regular URL. Their is also Thunderbird which have the firefox gecko engine: it can open web pages from hyperlinks in e-mails as new tabs.
Just a note, you can also use window.location.href (like in this answer: stackoverflow.com/questions/271171/…) to open the email client and it doesn't leave that empty window behind when the user has finished with the email.
Are subject and body variables or are they the actual text that will be in the fields?
that answer indeed doesn't answer question, but @rahulroy's answer is good
I would go one step further and do window.open( String( 'mailto:recipient^example.com' ).replace('^', '@') ); to confuse spam bots
M
MatthewMartin

Indirect via Your Server - Calling 3rd Party API - secure and recommended

Your server can call the 3rd Party API after proper authentication and authorization. The API Keys are not exposed to client.

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

const 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){
            
    let _name = req.body.name;
    let _email = req.body.email;
    let _subject = req.body.subject;
    let _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.

Directly From Client - Calling 3rd Party API - not recomended

Send an email using only JavaScript

in short:

register for Mandrill to get an API key load jQuery 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

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.


even though the article does say this i feel like it should be said here as well that even though this will work, there are some security issues as you need to send your api key to the client as well. this could be abused.
B
BarryCap

I couldn't find an answer that really satisfied the original question.

Mandrill is not desirable due to it's new pricing policy, plus it required a backend service if you wanted to keep your credentials safe.

It's often preferable to hide your email so you don't end up on any lists (the mailto solution exposes this issue, and isn't convenient for most users).

It's a hassle to set up sendMail or require a backend at all just to send an email.

I put together a simple free service that allows you to make a standard HTTP POST request to send an email. It's called PostMail, and you can simply post a form, use JavaScript or jQuery. When you sign up, it provides you with code that you can copy & paste into your website. Here are some examples:

JavaScript:

<form id="javascript_form">
    <input type="text" name="subject" placeholder="Subject" />
    <textarea name="text" placeholder="Message"></textarea>
    <input type="submit" id="js_send" value="Send" />
</form>

<script>

    //update this with your js_form selector
    var form_id_js = "javascript_form";

    var data_js = {
        "access_token": "{your access token}" // sent after you sign up
    };

    function js_onSuccess() {
        // remove this to avoid redirect
        window.location = window.location.pathname + "?message=Email+Successfully+Sent%21&isError=0";
    }

    function js_onError(error) {
        // remove this to avoid redirect
        window.location = window.location.pathname + "?message=Email+could+not+be+sent.&isError=1";
    }

    var sendButton = document.getElementById("js_send");

    function js_send() {
        sendButton.value='Sending…';
        sendButton.disabled=true;
        var request = new XMLHttpRequest();
        request.onreadystatechange = function() {
            if (request.readyState == 4 && request.status == 200) {
                js_onSuccess();
            } else
            if(request.readyState == 4) {
                js_onError(request.response);
            }
        };

        var subject = document.querySelector("#" + form_id_js + " [name='subject']").value;
        var message = document.querySelector("#" + form_id_js + " [name='text']").value;
        data_js['subject'] = subject;
        data_js['text'] = message;
        var params = toParams(data_js);

        request.open("POST", "https://postmail.invotes.com/send", true);
        request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

        request.send(params);

        return false;
    }

    sendButton.onclick = js_send;

    function toParams(data_js) {
        var form_data = [];
        for ( var key in data_js ) {
            form_data.push(encodeURIComponent(key) + "=" + encodeURIComponent(data_js[key]));
        }

        return form_data.join("&");
    }

    var js_form = document.getElementById(form_id_js);
    js_form.addEventListener("submit", function (e) {
        e.preventDefault();
    });
</script>

jQuery:

<form id="jquery_form">
    <input type="text" name="subject" placeholder="Subject" />
    <textarea name="text" placeholder="Message" ></textarea>
    <input type="submit" name="send" value="Send" />
</form>

<script>

    //update this with your $form selector
    var form_id = "jquery_form";

    var data = {
        "access_token": "{your access token}" // sent after you sign up
    };

    function onSuccess() {
        // remove this to avoid redirect
        window.location = window.location.pathname + "?message=Email+Successfully+Sent%21&isError=0";
    }

    function onError(error) {
        // remove this to avoid redirect
        window.location = window.location.pathname + "?message=Email+could+not+be+sent.&isError=1";
    }

    var sendButton = $("#" + form_id + " [name='send']");

    function send() {
        sendButton.val('Sending…');
        sendButton.prop('disabled',true);

        var subject = $("#" + form_id + " [name='subject']").val();
        var message = $("#" + form_id + " [name='text']").val();
        data['subject'] = subject;
        data['text'] = message;

        $.post('https://postmail.invotes.com/send',
            data,
            onSuccess
        ).fail(onError);

        return false;
    }

    sendButton.on('click', send);

    var $form = $("#" + form_id);
    $form.submit(function( event ) {
        event.preventDefault();
    });
</script>

Again, in full disclosure, I created this service because I could not find a suitable answer.


I was looking for this solution, thanks for the answer but I wonder how can I add one more text box in the html form, because whenever I am trying to change the code to add one more text box for some other info ,the code stopped working. Do you know any solution for this.
This is the best solution. Thank you very much. Mandrill has no free plan anymore and mailgun doesn't support cors and thus JavaScript
Doesnt this have the same problem as others? Access token (API Key) is exposed
They have daily limit of 25 emails per day.
Should be back up now. Sorry about that!
P
Pissu Pusa

I know I am wayyy too late to write an answer for this question but nevertheless I think this will be use for anybody who is thinking of sending emails out via javascript.

The first way I would suggest is using a callback to do this on the server. If you really want it to be handled using javascript folowing is what I recommend.

The easiest way I found was using smtpJs. A free library which can be used to send emails.

1.Include the script like below

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

2. You can either send an email like this

Email.send({ Host : "smtp.yourisp.com", Username : "username", Password : "password", To : 'them@website.com', From : "you@isp.com", Subject : "This is the subject", Body : "And this is the body" }).then( message => alert(message) );

Which is not advisable as it will display your password on the client side.Thus you can do the following which encrypt your SMTP credentials, and lock it to a single domain, and pass a secure token instead of the credentials instead.

Email.send({ SecureToken : "C973D7AD-F097-4B95-91F4-40ABC5567812", To : 'them@website.com', From : "you@isp.com", Subject : "This is the subject", Body : "And this is the body" }).then( message => alert(message) );

Finally if you do not have a SMTP server you use an smtp relay service such as Elastic Email

Also here is the link to the official SmtpJS.com website where you can find all the example you need and the place where you can create your secure token.

I hope someone find this details useful. Happy coding.


This is still giving full access to your SMTP server to a third party so they can relay mail for you in exchange for … what?
The SecureToken is only valid for a domain that you specify when it is created, so calling the js from another domain will not work.
@smoore4 yeah but still they have to decrypt it on their server and they have access to your password and stuff. I wouldn't trust this service.
the most secure and the only way is to host your own service
Is the error Uncaught ReferenceError: Email is not defined expected? I'm pretty sure you didn't define Email. Or is it that you used a code snippet instead of just a code fence, and that we're not supposed to run it? Also I think you're not wayyy too late.
R
Ry-

You can find what to put inside the JavaScript function in this post.

function getAjax() {
    try {
        if (window.XMLHttpRequest) {
            return new XMLHttpRequest();
        } else if (window.ActiveXObject) {
            try {
                return new ActiveXObject('Msxml2.XMLHTTP');
            } catch (try_again) {
                return new ActiveXObject('Microsoft.XMLHTTP');
            }
        }
    } catch (fail) {
        return null;
    }
}

function sendMail(to, subject) {
     var rq = getAjax();

     if (rq) {
         // Success; attempt to use an Ajax request to a PHP script to send the e-mail
         try {
             rq.open('GET', 'sendmail.php?to=' + encodeURIComponent(to) + '&subject=' + encodeURIComponent(subject) + '&d=' + new Date().getTime().toString(), true);

             rq.onreadystatechange = function () {
                 if (this.readyState === 4) {
                     if (this.status >= 400) {
                         // The request failed; fall back to e-mail client
                         window.open('mailto:' + to + '?subject=' + encodeURIComponent(subject));
                     }
                 }
             };

             rq.send(null);
         } catch (fail) {
             // Failed to open the request; fall back to e-mail client
             window.open('mailto:' + to + '?subject=' + encodeURIComponent(subject));
         }
     } else {
         // Failed to create the request; fall back to e-mail client
         window.open('mailto:' + to + '?subject=' + encodeURIComponent(subject));
     }
}

Provide your own PHP (or whatever language) script to send the e-mail.


T
Tofandel

I am breaking the news to you. You CAN'T send an email with JavaScript per se.

Based on the context of the OP's question, my answer above does not hold true anymore as pointed out by @KennyEvitt in the comments. Looks like you can use JavaScript as an SMTP client.

However, I have not digged deeper to find out if it's secure & cross-browser compatible enough. So, I can neither encourage nor discourage you to use it. Use at your own risk.


could be done with ajax or even hidden iframes...you never know
@danialentzri: JavaScript will never be the mail relay, that's what I meant by "per se".
oops! I have a small monitor to tell you the truth and it doesn't support scrollbars.
@KennyEvitt from a quick glance I took, seems like you still need a mail relay. That's basically what I have said in my answer.
@Shef What did you see in your quick glance? I can't find a requirement for anything beyond what any other email client requires. Or are you claiming that, for example, Microsoft Outlook can't send email either? That's kinda technically true but not in any sense that I would expect anyone else to understand.
C
Christiaan Westerbeek

There seems to be a new solution at the horizon. It's called EmailJS. They claim that no server code is needed. You can request an invitation.

Update August 2016: EmailJS seems to be live already. You can send up to 200 emails per month for free and it offers subscriptions for higher volumes.


This is a bit of a bum steer, very pretty UI but stuff all documentation examples or help. Avoid.
I tried emailJS, but it sends only to my email. How can I send to any other email?
This is late but @MagedSaeed in the email templates section, when editing a template you can specify the "To" email. You can even make the "To" field dynamic using their templating option. Their docs do a good job detailing it.
Just integrated EmailJS into my React app. It works great and it was pretty smooth to install. The emails send directly to my desired email. Make sure you add reCAPTCHA. Thank you for this!
M
Megan Caithlyn

window.open('mailto:test@example.com'); as above does nothing to hide the "test@example.com" email address from being harvested by spambots. I used to constantly run into this problem.

var recipient="test";
var at = String.fromCharCode(64);
var dotcom="example.com";
var mail="mailto:";
window.open(mail+recipient+at+dotcom);

J
Jeremy Huiskamp

In your sendMail() function, add an ajax call to your backend, where you can implement this on the server side.


e
evilone

Javascript is client-side, you cannot email with Javascript. Browser recognizes maybe only mailto: and starts your default mail client.


that would explain why I couldn't find any info on it. Thank you!!
Same thing... Future API which could allow raw connection to a port are coming...
This is the most accurate answer! All of the other answers that make it sound possible, are using a back-end somewhere.. The OP said Javascript only. Meaning, No back-end please, even if it's a SAAS back-end. Great answer.
D
David

JavaScript can't send email from a web browser. However, stepping back from the solution you've already tried to implement, you can do something that meets the original requirement:

send an email without refreshing the page

You can use JavaScript to construct the values that the email will need and then make an AJAX request to a server resource that actually sends the email. (I don't know what server-side languages/technologies you're using, so that part is up to you.)

If you're not familiar with AJAX, a quick Google search will give you a lot of information. Generally you can get it up and running quickly with jQuery's $.ajax() function. You just need to have a page on the server that can be called in the request.


K
Kenny Evitt

It seems like one 'answer' to this is to implement an SMPT client. See email.js for a JavaScript library with an SMTP client.

Here's the GitHub repo for the SMTP client. Based on the repo's README, it appears that various shims or polyfills may be required depending on the client browser, but overall it does certainly seem feasible (if not actually significantly accomplished), tho not in a way that's easily describable by even a reasonably-long answer here.


S
Santhosh Menon

There is a combination service. You can combine the above listed solutions like mandrill with a service EmailJS, which can make the system more secure. They have not yet started the service though.


F
Fiach Reid

Another way to send email from JavaScript, is to use directtomx.com as follows;

 Email = {
 Send : function (to,from,subject,body,apikey)
    {
        if (apikey == undefined)
        {
            apikey = Email.apikey;
        }
        var nocache= Math.floor((Math.random() * 1000000) + 1);
        var strUrl = "http://directtomx.azurewebsites.net/mx.asmx/Send?";
        strUrl += "apikey=" + apikey;
        strUrl += "&from=" + from;
        strUrl += "&to=" + to;
        strUrl += "&subject=" + encodeURIComponent(subject);
        strUrl += "&body=" + encodeURIComponent(body);
        strUrl += "&cachebuster=" + nocache;
        Email.addScript(strUrl);
    },
    apikey : "",
    addScript : function(src){
            var s = document.createElement( 'link' );
            s.setAttribute( 'rel', 'stylesheet' );
            s.setAttribute( 'type', 'text/xml' );
            s.setAttribute( 'href', src);
            document.body.appendChild( s );
    }
};

Then call it from your page as follows;

 window.onload = function(){
    Email.apikey = "-- Your api key ---";
    Email.Send("to@domain.com","from@domain.com","Sent","Worked!");
 }

Just to add to this, an alternative way, assuming you have access to an SMTP server is to use this script at smtpjs.com/smtp.js, called as follows; Email.send("from@you.com", "to@them.com", "Subject", "Body.", "smtp.yourisp.com", "username", "password"); - See smtpjs.com
can you send html using smtp.js?
@AlejandroCorredor - Yes, you can send HTML emails via SMTPJS
directtomx.com's domain is for sale
A
Alireza

There is not a straight answer to your question as we can not send email only using javascript, but there are ways to use javascript to send emails for us:

1) using an api to and call the api via javascript to send the email for us, for example https://www.emailjs.com says that you can use such a code below to call their api after some setting:

var service_id = 'my_mandrill';
var template_id = 'feedback';
var template_params = {
name: 'John',
reply_email: 'john@doe.com',
message: 'This is awesome!'
};

emailjs.send(service_id,template_id,template_params);

2) create a backend code to send an email for you, you can use any backend framework to do it for you.

3) using something like:

window.open('mailto:me@http://stackoverflow.com/');

which will open your email application, this might get into blocked popup in your browser.

In general, sending an email is a server task, so should be done in backend languages, but we can use javascript to collect the data which is needed and send it to the server or api, also we can use third parities application and open them via the browser using javascript as mentioned above.


Re (1): I would be really reluctant to give my SMTP password to a tiny little company so they can send emails using my server in exchange for nothing more than my password. I'm not paying them. They have no strong motivation to keep the service running / really protect my credentials / not use my server for their spam.
S
Suhail Mumtaz Awan

If and only if i had to use some js library, i would do that with SMTPJs library.It offers encryption to your credentials such as username, password etc.


I would be really reluctant to give my SMTP password to a tiny little company so they can send emails using my server in exchange for nothing more than my password. I'm not paying them. They have no strong motivation to keep the service running / really protect my credentials / not use my server for their spam.
@Quentin i understood, but this library could be answer to the question.
P
P. BANERJEE

The short answer is that you can't do it using JavaScript alone. You'd need a server-side handler to connect with the SMTP server to actually send the mail. There are many simple mail scripts online, such as this one for PHP:

Use Ajax to send request to the PHP script ,check that required field are not empty or incorrect using js also keep a record of mail send by whom from your server.

function sendMail() is good for doing that.

Check for any error caught while mailing from your script and take appropriate action. For resolving it for example if the mail address is incorrect or mail is not send due to server problem or it's in queue in such condition report it to user immediately and prevent multi sending same email again and again. Get response from your script Using jQuery GET and POST

$.get(URL,callback); $.post(URL,callback);


S
Sercan Ozdemir

Since these all are wonderful infos there's a little api called Mandrill to send mails from javascript and it works perfectly. You can give it a shot. Here's a little tutorial for the start.


A
Anil Rathod

Send an email using the JavaScript or jQuery

var ConvertedFileStream;
var g_recipient;
var g_subject;
var g_body;
var g_attachmentname;


function SendMailItem(p_recipient, p_subject, p_body, p_file, p_attachmentname, progressSymbol) {

    // Email address of the recipient 
    g_recipient = p_recipient;

   // Subject line of an email
    g_subject = p_subject;

   // Body description of an email
    g_body = p_body;

    // attachments of an email
    g_attachmentname = p_attachmentname;

    SendC360Email(g_recipient, g_subject, g_body, g_attachmentname);

}

function SendC360Email(g_recipient, g_subject, g_body, g_attachmentname) {
    var flag = confirm('Would you like continue with email');
    if (flag == true) {

        try {
            //p_file = g_attachmentname;
            //var FileExtension = p_file.substring(p_file.lastIndexOf(".") + 1);
           // FileExtension = FileExtension.toUpperCase();
            //alert(FileExtension);
            SendMailHere = true;

            //if (FileExtension != "PDF") {

            //    if (confirm('Convert to PDF?')) {
            //        SendMailHere = false;                    
            //    }

            //}
            if (SendMailHere) {
                var objO = new ActiveXObject('Outlook.Application');

                var objNS = objO.GetNameSpace('MAPI');

                var mItm = objO.CreateItem(0);

                if (g_recipient.length > 0) {
                    mItm.To = g_recipient;
                }

                mItm.Subject = g_subject;

                // if there is only one attachment                 
                // p_file = g_attachmentname;
                // mAts.add(p_file, 1, g_body.length + 1, g_attachmentname);

                // If there are multiple attachment files
                //Split the  files names
                var arrFileName = g_attachmentname.split(";");
                 // alert(g_attachmentname);
                //alert(arrFileName.length);
                var mAts = mItm.Attachments;

                for (var i = 0; i < arrFileName.length; i++)
                {
                    //alert(arrFileName[i]);
                    p_file = arrFileName[i];
                    if (p_file.length > 0)
                    {                     
                        //mAts.add(p_file, 1, g_body.length + 1, g_attachmentname);
                        mAts.add(p_file, i, g_body.length + 1, p_file);

                    }
                }

                mItm.Display();

                mItm.Body = g_body;

                mItm.GetInspector.WindowState = 2;

            }
            //hideProgressDiv();

        } catch (e) {
            //debugger;
            //hideProgressDiv();
            alert('Unable to send email.  Please check the following: \n' +
                    '1. Microsoft Outlook is installed.\n' +
                    '2. In IE the SharePoint Site is trusted.\n' +
                    '3. In IE the setting for Initialize and Script ActiveX controls not marked as safe is Enabled in the Trusted zone.');
        }
    }
  }

Please elaborate on how this code answers the question.
It looks like this is using ActiveX and only works in IE on a PC with Outlook installed var objO = new ActiveXObject('Outlook.Application');
I think that's quite “gold”. Whatever this means.