Last active
November 20, 2022 14:08
-
-
Save HeyMehedi/8a9a51506fc22fb330dc1e8b293376f8 to your computer and use it in GitHub Desktop.
Email Files Directory to Email List for PHP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?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