Export all user mail addresses to CSV



/**
 * Implements hook_menu().
 */
function export_mails_menu() {
  return array(
    'export_mails.csv' => array(
      'page callback' => '_export_mails',
      'access callback' => 'user_is_logged_in',
    ),
  );
}

/**
 * Implements hook_block_info().
 */
function export_mails_block_info() {

  $blocks['export_mails'] = array(
    'info' => t('Export mails'),
  );

  return $blocks;

}

/**
 * Implements hook_block_view().
 */
function export_mails_block_view($delta) {
  switch ($delta) {
    case 'export_mails' :
      return array(
        'subject' => t('Export mails.'),
        'content' => drupal_get_form('export_mails_form'),
      );
      break;
  }
}

/**
 * Implements hook_form().
 */
function export_mails_form($node, &$form_state) {
  $form = array();
   
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Export mails')
  );
   
  return $form;
}

/**
 * export_mails_form submit handler.
 * 
 * Serve the export_mails.csv file.
 * As we are sure there's nothing left to be executed, it is safe to use a drupal_goto().
 * 
 */
function export_mails_form_submit($node, &$form_state) {
  drupal_goto('export_mails.csv');
}

/**
 * Get all order related email addresses.
 * And pass them to a CSV file, which is served to the browser.
 * 
 */
function _export_mails() {
  
  // Load all users except anonymous user 0, which doesn't have an email address.
  $mails = db_select('users', 'u')
  ->fields('u', array('mail'))
  ->condition('uid', 0, '<>')
  ->execute()->fetchCol();
  
  // Serve the CSV file as a browser attachment.
  drupal_add_http_header('Content-Type','text/plain; charset=UTF-8');
  drupal_add_http_header('Content-Disposition','attachment; filename="mails.csv"');
  foreach ($mails as $mail) {
    // We need the double quotes on \r\n, if not, line breaks aren't created.
    print $mail . "\r\n";
  }
}

Add new comment

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.