Creating a dynamic contact form for an S3 static website using AWS
Creating a dynamic contact form for an S3 static website using AWS, Amazon API Gateway, and Amazon SES involves several steps. Below is a high-level guide to help you through the process:
### Step 1: Set Up Your Static Website on S3
1. **Create an S3 Bucket:**
- Go to the S3 console and create a new bucket. Make sure to follow the naming conventions and set appropriate permissions.
2. **Enable Static Website Hosting:**
- In the bucket properties, enable static website hosting and specify the index document (e.g., `index.html`).
3. **Upload Your Website Files:**
- Upload your HTML, CSS, and JavaScript files to the S3 bucket.
### Step 2: Create the Contact Form
1. **HTML Form:**
```html
<form id="contact-form">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<label for="message">Message:</label>
<textarea id="message" name="message" required></textarea>
<button type="submit">Send</button>
</form>
<script src="form.js"></script>
```
2. **JavaScript to Handle Form Submission:**
```javascript
document.getElementById('contact-form').addEventListener('submit', async function(event) {
event.preventDefault();
const formData = {
name: document.getElementById('name').value,
email: document.getElementById('email').value,
message: document.getElementById('message').value
};
try {
const response = await fetch('https://<API_GATEWAY_ENDPOINT>', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(formData)
});
if (response.ok) {
alert('Message sent successfully!');
} else {
alert('Failed to send message.');
}
} catch (error) {
console.error('Error:', error);
alert('Error sending message.');
}
});
```
### Step 3: Set Up AWS Lambda
1. **Create Lambda Function:**
- Go to the Lambda console and create a new function.
- Choose `Author from scratch`, and set the runtime to Node.js (or your preferred language).
2. **Add Code to Lambda Function:**
```javascript
const AWS = require('aws-sdk');
const ses = new AWS.SES({ region: 'us-east-1' });
exports.handler = async (event) => {
const { name, email, message } = JSON.parse(event.body);
const params = {
Destination: {
ToAddresses: ['your-email@example.com']
},
Message: {
Body: {
Text: { Data: `Name: ${name}\nEmail: ${email}\nMessage: ${message}` }
},
Subject: { Data: 'New Contact Form Submission' }
},
Source: 'your-verified-email@example.com'
};
try {
await ses.sendEmail(params).promise();
return {
statusCode: 200,
body: JSON.stringify({ message: 'Email sent successfully' })
};
} catch (error) {
return {
statusCode: 500,
body: JSON.stringify({ error: 'Failed to send email' })
};
}
};
```
### Step 4: Create API Gateway
1. **Create a New REST API:**
- Go to the API Gateway console and create a new REST API.
2. **Create a Resource and Method:**
- Create a new resource (e.g., `/contact`).
- Add a `POST` method to the resource.
- Set the Integration type to Lambda Function and select the Lambda function created earlier.
3. **Enable CORS:**
- Enable CORS on the resource to allow your S3 hosted site to call the API.
4. **Deploy the API:**
- Create a new deployment stage (e.g., `prod`) and deploy your API.
### Step 5: Test and Verify
1. **Update the JavaScript Fetch URL:**
- Replace `<API_GATEWAY_ENDPOINT>` in the JavaScript with the actual endpoint URL of your deployed API.
2. **Test the Form:**
- Open your static website and test the form by submitting it.
- Check your email to see if the message was received.
By following these steps, you'll have a dynamic contact form on your S3 static website that uses AWS Lambda, Amazon API Gateway, and Amazon SES to send emails.
Check out our form backend service
https://fabform.io