如何从静态输入文本创建电子邮件正文?

时间:2019-01-25 00:52:59

标签: javascript html

我想在静态页面上创建文本输入表单,然后使用mailto选项将其转换为电子邮件正文。例如,以下带有来自文本框

的输入
<form action="/action_page.php">
  First name:<br>
  <input type="text" name="firstname" value="Mickey"><br>
  Last name:<br>
  <input type="text" name="lastname" value="Mouse"><br><br>
  <input type="submit" value="Submit">
</form>

,并且在电子邮件正文中将显示为

Hello ABC,

The details are:

First Name: Mickey
Last Name: Mouse

Thanks,
XYZ

1 个答案:

答案 0 :(得分:1)

我已经花时间为您总结了一些答案。希望您能花些时间仔细阅读所提供的每个链接。

首先,您要获得form data as an object

const formToJSON = elements => [].reduce.call(elements, (data, element) => {  
  data[element.name] = element.value;
  return data;
}, {});

我使用destructuring assignment设置了mailto中使用的一些常量的默认值:

const { 
  recipientName = "ABC", recipientAddress = "abc@123.yes",
  subject = "Some mailz for youz", senderName = "XYZ",
  firstname = "first", lastname = "last"
} = formToJSON(document.querySelectorAll("form input:not([type='submit'])"))

我们还需要一些linebreaks in our email body

const lineBreak = "%0D%0A"

最后template literals来构建我们的href for mailto

const mailTo = `mailto:${recipientAddress}?subject=${subject}&body=Hello ABC,${lineBreak}
I am your father.${lineBreak}${lineBreak}
The details are:${lineBreak}${lineBreak}
First Name: ${firstname}${lineBreak}
Last Name: ${lastname}${lineBreak}${lineBreak}
Thanks,${lineBreak}
${senderName}`

这是代码段,因此您可以看到它们一起工作:

const formToJSON = elements => [].reduce.call(elements, (data, element) => {  
  data[element.name] = element.value;
  return data;
}, {});

const { 
  recipientName = "ABC", recipientAddress = "abc@123.yes",
  subject = "Some mailz for youz", senderName = "XYZ",
  firstname = "first", lastname = "last"
} = formToJSON(document.querySelectorAll("form input:not([type='submit'])"))

const lineBreak = "%0D%0A"

const mailTo = `mailto:${recipientAddress}?subject=${subject}&body=Hello ABC,${lineBreak}
I am your father.${lineBreak}${lineBreak}
The details are:${lineBreak}${lineBreak}
First Name: ${firstname}${lineBreak}
Last Name: ${lastname}${lineBreak}${lineBreak}
Thanks,${lineBreak}
${senderName}`

const link = document.createElement("a")
link.textContent = "Send some mailz yaaaal"
link.href = mailTo
document.body.appendChild(link)
<form action="/action_page.php">
  First name:<br>
  <input type="text" name="firstname" value="Mickey"><br>
  Last name:<br>
  <input type="text" name="lastname" value="Mouse"><br><br>
  <input type="submit" value="Submit">
</form>