Skip to content

Instantly share code, notes, and snippets.

@HeyMehedi
Last active November 20, 2022 14:08
Show Gist options
  • Select an option

  • Save HeyMehedi/8a9a51506fc22fb330dc1e8b293376f8 to your computer and use it in GitHub Desktop.

Select an option

Save HeyMehedi/8a9a51506fc22fb330dc1e8b293376f8 to your computer and use it in GitHub Desktop.
Email Files Directory to Email List for PHP
<?php
$dir = __DIR__ . '/emails';
$emails = scandir( $dir );
$output = fopen( 'output.csv', 'w' );
function extract_email( $text ) {
//String that recognizes an e-mail
$str = '/([a-z0-9_\.\-])+\@(([a-z0-9\-])+\.)+([a-z0-9]{2,4})+/i';
preg_match_all( $str, $text, $out );
//return a blank array if not true otherwise insert the email in $out and return
return isset( $out[0][0] ) ? $out[0][0] : '';
}
function extract_name( $text ) {
$pos = strpos( $text, 'Name: ' );
if ( $pos === 0 ) {
$single_name = str_replace( array( 'Name: ' ), '', $text );
return trim( $single_name );
}
return '';
}
fputcsv( $output, array( 'email', 'first_name' ), ",", " " );
foreach ( $emails as $eml ) {
$single_name = '';
$single_email = '';
$filename = $dir . '/' . $eml;
if ( is_file( $filename ) ) {
$content = file_get_contents( $filename );
$lines = explode( "\n", $content );
foreach ( $lines as $num => $line ) {
$text = strip_tags( $line );
$email = strpos( $text, 'Email: ' );
$name = strpos( $text, 'Name: ' );
if ( $name !== false ) {
$single_name = extract_name( $text );
}
if ( $email !== false ) {
$single_email = extract_email( $text );
}
}
fputcsv( $output, array( $single_email, $single_name ), ",", " " );
}
}
fclose( $output );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment