Archive
extract e-mails from a file
Problem
You have a text file and you want to extract all the e-mail addresses from it. For research purposes, of course.
Solution
#!/usr/bin/env python3
import re
import sys
def extract_emails_from(fname):
with open(fname, errors='replace') as f:
for line in f:
match = re.findall(r'[\w\.-]+@[\w\.-]+', line)
for e in match:
if '?' not in e:
print(e)
def main():
fname = sys.argv[1]
extract_emails_from(fname)
##############################################################################
if __name__ == "__main__":
if len(sys.argv) == 1:
print("Error: provide a text file!", file=sys.stderr)
exit(1)
# else
main()
I had character encoding problems with some lines where the original program died with an exception. Using “open(fname, errors='replace')” will replace problematic characters with a “?“, hence the extra check before printing an e-mail to the screen.
The core of the script is the regex to find e-mails. That tip is from here.
email notification from a script
Problem
You want to send an email to yourself from a script.
Solution
You can find here how to do it from a Bash script. That solution uses the mailx command.
Here is a simple Python wrapper for the mailx command:
#!/usr/bin/env python3
# coding: utf8
import os
DEBUG = True
# DEBUG = False
class NoSubjectError(Exception):
pass
class NoRecipientError(Exception):
pass
def send_email(to='', subject='', body=''):
if not subject:
raise NoSubjectError
if not to:
raise NoRecipientError
#
if not body:
cmd = """mailx -s "{s}" < /dev/null "{to}" 2>/dev/null""".format(
s=subject, to=to
)
else:
cmd = """echo "{b}" | mailx -s "{s}" "{to}" 2>/dev/null""".format(
b=body, s=subject, to=to
)
if DEBUG:
print("#", cmd)
#
os.system(cmd)
def main():
send_email(to="[email protected]",
subject="subject")
#
send_email(to="[email protected]",
subject="subject",
body='this is the body of the email')
#############################################################################
if __name__ == "__main__":
main()
You can also find this code as a gist.
find out a github user’s (hidden) email address
Problem
You want to contact someone on GitHub but (s)he doesn’t indicate his/her email on the profile page. What to do?
Solution
Figure it out :) The manual steps are indicated here. I made a Python script of it that can be found here: https://github.com/jabbalaci/Bash-Utils/blob/master/github_user_email.py .
Usage example:
$ ./github_user_email.py Github info (username or repo. link): https://github.com/jabbalaci/Bash-Utils [email protected]
If you want to hide your email address, then here are some tips.
