Skip to content

Instantly share code, notes, and snippets.

@stokito
Last active May 22, 2022 14:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stokito/4d6682ddcf55019f6954e7f0a8856983 to your computer and use it in GitHub Desktop.
Save stokito/4d6682ddcf55019f6954e7f0a8856983 to your computer and use it in GitHub Desktop.
Parse EMail message in JavaScript sample
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>EMail message parse in JavaScript sample</title>
<script>
function addHeader(header, headers) {
if (header === "") {
return
}
let headerValStart = header.indexOf(":")
let headerKey = header.substring(0, headerValStart)
let headerVal = header.substring(headerValStart + 1).trimStart()
headers[headerKey] = headerVal
}
/**
* @param {string} msgBody
*/
function parseEnvelope(msgBody) {
let headers = {}
let lineStart = 0
let header = ""
for (let i = 0; i < msgBody.length; i++) {
let lineEnd = msgBody.indexOf("\r\n", lineStart)
if (lineEnd === -1) {
break
}
let line = msgBody.substring(lineStart, lineEnd)
lineStart = lineEnd + 2 // skip CRLF
if (line === "") {
addHeader(header, headers);
break
}
let lineTrim = line.trimStart()
if (lineTrim.length < line.length) {
header += " " + lineTrim
} else {
addHeader(header, headers);
header = line
}
}
let body = msgBody.substring(lineStart)
return {headers, body};
}
function parseMail() {
let msgBody = document.getElementById("msgBody").value
let {headers, body} = parseEnvelope(msgBody)
console.log(headers)
console.log(body)
document.getElementById("from").innerText = headers["From"]
document.getElementById("to").innerText = headers["To"]
}
</script>
</head>
<body>
<div>
<button onclick="parseMail();">parse</button>
<span id="from"></span>
<span id="to"></span>
</div>
<textarea id="msgBody" style="width: 100%" rows="250">
MIME-Version: 1.0
From: Some Sender <sender@example.com>
Date: Mon, 16 May 2022 02:09:08 +0300
Subject: Greetings
To: recepient@example.com
Content-Type: text/plain; charset="UTF-8"
Hello
</textarea>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment