Ajax mail action email attachment
A very specific question!
To send an email with an attachment using AJAX and JavaScript, you can use the following approach:
Step 1: Create a form
Create a form with a file input field and a submit button. The form will be used to send the email with the attachment.
<form id="email-form">
<input type="file" id="attachment" name="attachment">
<button type="submit">Send Email</button>
</form>
Step 2: Write the JavaScript code
Use the XMLHttpRequest
object or the fetch
API to send the email with the attachment. You'll need to set the Content-Type
header to multipart/form-data
to indicate that the request contains a file.
const form = document.getElementById('email-form');
const attachmentInput = document.getElementById('attachment');
form.addEventListener('submit', (e) => {
e.preventDefault();
const formData = new FormData(form);
const xhr = new XMLHttpRequest();
xhr.open('POST', 'email.php', true);
xhr.setRequestHeader('Content-Type', 'multipart/form-data');
xhr.send(formData);
});
Step 3: Handle the email sending
In your server-side script (e.g., PHP), handle the email sending by processing the form data and attaching the file. You can use a library like PHPMailer to send the email.
<?php
// email.php
$attachment = $_FILES['attachment'];
$email = new PHPMailer();
$email->setFrom('[email protected]');
$email->addAddress('[email protected]');
$email->Subject = 'Email with attachment';
$email->Body = 'This is the email body';
$email->addAttachment($attachment['tmp_name'], $attachment['name']);
$email->send();
echo 'Email sent successfully!';
?>
Step 4: Handle the response
In your JavaScript code, handle the response from the server by displaying a success message or an error message.
xhr.onload = () => {
if (xhr.status === 200) {
console.log('Email sent successfully!');
} else {
console.error('Error sending email:', xhr.statusText);
}
};
That's it! With these steps, you should be able to send an email with an attachment using AJAX and JavaScript.