Utilize this code to integrate the Mandrill API for sending emails from a website. The issue at hand is incorporating HTML input into the JSON format required to send the email to the correct address. Take a look at the following code snippet:
<head>
<script type="text/javascript" src="https://mandrillapp.com/api/docs/js/mandrill.js"></script>
<script type="text/javascript" src="send-email.js"></script>
</head>
<body>
<input type="text" value="email" id="maila"/>
<button onclick="sendTheMail(); return false;">Send Email</button>
<pre id="response"></pre>
</body>
The above code contains HTML where users can input an email address to which they want to send an email.
Next, we have a JavaScript (.js) file as follows:
function log(obj) {
$('#response').text(JSON.stringify(obj));
}
var m = new mandrill.Mandrill('API-KEY');
var mailaddress = document.getElementById("maila").value;
var params = {
"message": {
"from_email":"example@example.com",
"to":[{"email":"recipient@example.com"}],
"subject": "Sending you an email",
"html": "Body of the email goes here"
}
};
function sendTheMail() {
m.messages.send(params, function(res) {
log(res);
}, function(err) {
log(err);
});
}
In the above JavaScript, the variable `mailaddress` fetches the user-entered email address. To include this dynamic email address in place of `"recipient@example.com"`, modifications are needed since directly inserting the variable won't work due to incompatible data types.
I've tested and verified the program's functionality by manually inserting an email address, and it successfully sends out emails. Although I’ve scoured forums and search engines for solutions on this issue, unfortunately, no clear-cut solution has been found.
UPDATE I have managed to resolve the issue with your valuable input. I believe the getElementById function needs to be encapsulated within a specific function, leading me to make slight adjustments to the code structure. Here’s the updated and functional code:
function log(obj) {
$('#response').text(JSON.stringify(obj));
}
var m = new mandrill.Mandrill('API-KEY');
function sendTheMail() {
var mailaddress = document.getElementById("maila").value,
recipient = [{"email": String(mailaddress)}];
var params = {
"message": {
"from_email": "sender@example.com",
"to": recipient,
"subject": "Sending an email using Mandrill API",
"text": "Learning Mandrill API through practical exercises.",
"autotext": true
}
};
m.messages.send(params, function(res) {
log(res);
}, function(err) {
log(err);
});
}