Send email script html

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.

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.

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.

20 Answers 20

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.

Читайте также:  Невозможно найти пакет python pyric

I would go one step further and do window.open( String( ‘mailto:recipient^example.com’ ).replace(‘^’, ‘@’) ); to confuse spam bots

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

Your server can call the 3rd Party API. The API Keys are not exposed to client.

const axios = require('axios'); async function sendEmail(name, email, subject, message) < const data = JSON.stringify(< "Messages": [< "From": ", "Name": "">, "To": [], "Subject": subject, "TextPart": message >] >); const config = < method: 'post', url: 'https://api.mailjet.com/v3.1/send', data: data, headers: , auth: ', password: ''>, >; return axios(config) .then(function (response) < console.log(JSON.stringify(response.data)); >) .catch(function (error) < console.log(error); >); > // define your own email api which points to your server. app.post('/api/sendemail/', function (req, res) < const = req.body; //implement your spam protection or checks. sendEmail(name, email, subject, message); >); 

and then use use fetch on client side to call your email API. Use from email which you used to register on Mailjet. You can authenticate more addresses too. Mailjet offers a generous free tier.

Update 2023: As pointed out in the comments the method below does not work any more due to CORS

This can be only useful if you want to test sending email and to do this

  • visit https://api.mailjet.com/stats (yes a 404 page)
  • and run this code in the browser console (with the secrets populated)

Directly From Client — Calling 3rd Party API — not recommended

  1. register for Mailjet to get an API key and Secret
  2. use fetch to call API to send an email
function sendMail(name, email, subject, message) < const myHeaders = new Headers(); myHeaders.append("Content-Type", "application/json"); myHeaders.set('Authorization', 'Basic ' + btoa(''+":" +'')); const data = JSON.stringify(< "Messages": [< "From": ", "Name": "">, "To": [], "Subject": subject, "TextPart": message >] >); const requestOptions = < method: 'POST', headers: myHeaders, body: data, >; fetch("https://api.mailjet.com/v3.1/send", requestOptions) .then(response => response.text()) .then(result => console.log(result)) .catch(error => console.log('error', error)); > sendMail('Test Name',"",'Test Subject','Test Message') 

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.

Читайте также:  Java constants class file

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:

 
 

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

Источник

Отправка писем с помощью JavaScript

Отправка писем с помощью JavaScript

JavaScript – это язык программирования, который можно использовать как для интерфейсной, так и для внутренней разработки. Когда JavaScript упоминается в контексте отправки электронных писем, Node.js – это первое, что приходит на ум. И сегодня мы разберем, как использовать JS для отправки электронных писем из приложения, у которого нет сервера.

FAQ: Могу ли я отправлять электронные письма с JS или нет?

Вы не можете отправлять электронные письма, используя только код JavaScript, из-за отсутствия поддержки серверных соединений. Для этого вам понадобится серверный язык, который общается с SMTP-сервером. Вы можете использовать JS вместе с серверным скриптом, который будет отправлять электронные письма из браузера на основе ваших запросов.

Почему вы можете захотеть отправлять электронные письма с помощью JS

Традиционно серверная часть обычного приложения отвечает за отправку электронных писем. Вам нужно будет настроить сервер с использованием внутренней технологии. Клиентская сторона отправляет запрос на сервер, который создает электронное письмо и отправляет его на SMTP-сервер.

Итак, почему кто-то может пойти другим путем и отправлять электронные письма прямо со стороны клиента с помощью JavaScript? Такой подход весьма полезен для создания контактных форм или других видов взаимодействия с пользователем в веб-приложениях, что позволяет вашему приложению отправлять электронную почту без обновления страницы, с которой взаимодействует пользователь. Кроме того, вам не нужно возиться с кодированием сервера. Это веский аргумент, если ваше веб-приложение использует отправку электронной почты только для контактных форм. Ниже вы найдете несколько вариантов того, как заставить ваше приложение отправлять электронные письма со стороны клиента.

Читайте также:  Python get today datetime

mailto: для отправки формы данных

Поскольку вы не можете отправить электронное письмо напрямую с помощью JS, вы можете указать браузеру открыть для этого почтовый клиент по умолчанию. Технически метод mailto: не отправляет электронную почту прямо из браузера, но может выполнять следующую работу:

Когда вы запустите код в браузере, вы увидите следующее:

После отправки данных браузер открывает почтовый клиент по умолчанию. В нашем случае это Gmail.

Метод mailto: является довольно простым решением для реализации , но он имеет некоторые специфические недостатки:

  • Вы не можете контролировать макет данных, поскольку данные отправляются в форме, отправленной браузером.
  • mailto: не защищает ваш адрес электронной почты от спам-ботов. Некоторое время назад это можно было смягчить, построив ссылку в JS. В наши дни все больше и больше ботов запускают JS и не полагаются на HTML, отображаемый только сервером.

SmtpJS.com – отправка писем из JavaScript

SmtpJS – это бесплатная библиотека, которую вы можете использовать для отправки писем из JavaScript. Все, что вам нужно, – это SMTP-сервер и несколько манипуляций, чтобы все было сделано. Мы будем использовать Mailtrap.io в качестве сервера, потому что это действенное решение для тестирования электронной почты. Ниже приведен порядок действий, которому вы должны следовать:

  • Создайте HTML-файл (например, test.html) со следующим скриптом:
  • Создайте кнопку, которая будет запускать функцию JavaScript.
  • Напишите функцию JS для отправки писем через SmtpJS.com.
Email.send(< Host : "smtp.mailtrap.io", Username : "", Password : "", To : 'recipient@example.com', From : "sender@example.com", Subject : "Test email", Body : "

Header

Bold text Italic" >).then( message => alert(message) ); >

Недостатком приведенного выше примера является то, что ваше имя пользователя и пароль видны в клиентском скрипте. Это можно исправить, если использовать параметр шифрования, предоставляемый SmtpJS. Нажмите кнопку «Зашифровать свои учетные данные SMTP» и заполните необходимые поля.

После этого нажмите “Сгенерировать токен безопасности” и затем используйте его в своей функции JS вместо настроек SMTP-сервера, как показано ниже:

Источник

Оцените статью