How to send mail from static html page
To send mail from a static HTML page, you'll need to use a combination of HTML, JavaScript, and a mail service API. Here's a step-by-step guide to help you achieve this:
Step 1: Create a form in your HTML page
Add a form to your HTML page with the necessary fields (e.g., name, email, message). Make sure to set the action
attribute to a JavaScript function that will handle the form submission.
<form id="contact-form">
<label for="name">Name:</label>
<input type="text" id="name" name="name"><br><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email"><br><br>
<label for="message">Message:</label>
<textarea id="message" name="message"></textarea><br><br>
<input type="submit" value="Send">
</form>
Step 2: Write a JavaScript function to handle form submission
Create a JavaScript function that will be called when the form is submitted. This function will collect the form data, prepare the email, and send it using a mail service API.
function sendMail() {
// Get the form data
var name = document.getElementById("name").value;
var email = document.getElementById("email").value;
var message = document.getElementById("message").value;
// Prepare the email
var subject = "Contact Form Submission";
var body = "Name: " + name + "\nEmail: " + email + "\nMessage: " + message;
// Use a mail service API to send the email
// For example, using Mailgun's API
var mailgun = require('mailgun-js');
var mg = mailgun({
apiKey: 'YOUR_API_KEY',
domain: 'YOUR_DOMAIN'
});
mg.messages().send({
from: '[email protected]',
to: '[email protected]',
subject: subject,
text: body
}, function (error, body) {
if (error) {
console.log(error);
} else {
console.log(body);
}
});
}
Step 3: Add an event listener to the form
Add an event listener to the form's submit
event to call the sendMail
function when the form is submitted.
document.getElementById("contact-form").addEventListener("submit", sendMail);
Step 4: Set up a mail service API
Choose a mail service API that supports sending emails from a static HTML page. Some popular options include:
- Mailgun: A popular email service that provides a simple API for sending emails.
- Sendgrid: A cloud-based email service that offers a robust API for sending emails.
- Amazon SES: A scalable email service offered by Amazon Web Services.
Sign up for an account with one of these services and obtain an API key. You'll need to use this API key in your JavaScript code to send emails.
Step 5: Test your code
Test your code by submitting the form on your HTML page. If everything is set up correctly, you should receive an email at the recipient's email address.
That's it! With these steps, you should be able to send mail from a static HTML page using a mail service API.