1

I'm not a new coder, but new to google app scripts. I am trying to take a string and find the email address contained within the string.

string = "This is the body of the cell where I will be looking. This body has an email in it somewhere like [email protected] here.";

email = FindEmail(string);

MailApp.sendEmail(email, "Completion Email", "", "this is the email message");

I need to build a function called FindEmail but frankly have no idea how to start.

4
  • Find the position of the '@' and then find the nearest preceding and following space? Whatever is in between that range is most likely you're email address. Commented Jul 30, 2013 at 15:12
  • i don't know the code to do that. Commented Jul 30, 2013 at 15:13
  • 2
    Although you're using Google Apps Script, the operation you're doing is entirely Javascript, so this question is a duplicate of How to find out emails and names out of a string in javascript. Commented Jul 30, 2013 at 15:14
  • See also this and this... and probably others! Commented Jul 30, 2013 at 15:52

2 Answers 2

4

While there are numerous solutions to this on SO already, the ones I've found need tweaking to provide the simplicity you're looking for.

Here's a simple function condensed from all those other answers - the regular expression is a bit of overkill, actually, but can also be used to validate in many cases. It returns an array of addresses, so if you only want the first one, you would code email = findEmails(string)[0]... but really, you should do some error checking before trusting that.

/**
 * Return an array of all email addresses found in input string.
 */
function FindEmails(input) {
  var regex = /(?:[a-z0-9!#$%&'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+\/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])/gm
  var result = input.match(regex);
  return result;
}
Sign up to request clarification or add additional context in comments.

Comments

1

An email address parsing library "email-addresses" has been adapted for Google Apps Script. Source is forked and available as a gist.

  • Publicly available, library key M26NvEFUvGLQadhq7G3OQmgFzUAA6_aCl.
  • Documentation available here.

However... it will not find the email address in the string example you give! It expects the string containing addresses to loosely conform to RFC 5322.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.