Importing emails to wordpress

I have created a PHP script that is supposed to import emails into WordPress automatically and from specific accounts with specific senders.

Some emails cannot be imported even if the same account is used. Some emails from the same sender can be imported, others cannot.

In Microsoft Outlook, I see that the messages are marked as read, but when I try to modify the email in Outlook, it seems as if the email is locked on the server and I have to restart MS Outlook to be able to change the email.

So, some emails can be imported just fine, others cannot. Any suggestions for a solution? I do not receive any error messages.
I would be happy if anyone could help me solve this issue.

This is the importer:

<?php
ini_set('max_execution_time', 300);
require_once 'post-creator.php';

function email_to_post_importer_import_emails() {
    set_time_limit(300);

    $options = get_option('email_to_post_importer_options');
    $accounts = isset($options['accounts']) ? $options['accounts'] : array();

    foreach ($accounts as $account) {
        $emails = email_to_post_importer_fetch_emails($account);

        foreach ($emails as $email) {
            email_to_post_importer_create_post($email);
        }

        sleep(5);
    }
}

function getPart($inbox, $email_id, $part, $partNumber = '') {
    if ($part->subtype == 'PLAIN') {
        return imap_fetchbody($inbox, $email_id, $partNumber);
    } else if ($part->subtype == 'HTML') {
        return imap_fetchbody($inbox, $email_id, $partNumber);
    }

    if ($part->type == 1) {
        foreach ($part->parts as $index => $subPart) {
            $result = getPart($inbox, $email_id, $subPart, $partNumber . '.' . ($index + 1));
            if ($result != null) {
                return $result;
            }
        }
    }

    return null;
}

function decode_base64_if_needed($content) {
    $decoded = base64_decode($content, true);
    if ($decoded !== false && mb_check_encoding($decoded, 'UTF-8')) {
        return $decoded;
    }
    return $content;
}

function extract_sender_ip($header) {
    if (!isset($header->Received) || $header->Received === null) {
        return null;  // or you can return a default value or handle it differently
    }
    
    preg_match_all('/\[(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\]/', $header->Received, $matches);
    if (!empty($matches[1])) {
        return end($matches[1]);
    }
    return null;
}

function email_to_post_importer_fetch_emails($account) {
    $email_ssl_tls = $account['encryption'];
    $mailbox = "{" . $account['server'] . ":" . $account['port'] . "/imap/ssl/novalidate-cert" . "}INBOX";
    $username = $account['email'];
    $password = decrypt_password($account['password'], EMAIL_TO_POST_IMPORTER_SECRET_KEY);    
    $inbox = imap_open($mailbox, $username, $password) or die('Error: ' . imap_last_error());
    $emails = array();

    if ($inbox) {
        $emails_ids = imap_search($inbox, 'UNSEEN FROM "' . $account['sender_email'] . '"');
        if ($emails_ids) {
            foreach ($emails_ids as $email_id) {
                $overview = imap_fetch_overview($inbox, $email_id, 0);
                $header = imap_headerinfo($inbox, $email_id);
                $sender_ip = extract_sender_ip($header);
                $structure = imap_fetchstructure($inbox, $email_id);
                $final_body = '';

                if (isset($structure->parts)) {
                    for ($i = 0; $i < count($structure->parts); $i++) {
                        $body = getPart($inbox, $email_id, $structure->parts[$i], $i + 1);
                        if ($body != null) {
                            $final_body = $body;
                            break;
                        }
                    }
                } else {
                    $final_body = imap_fetchbody($inbox, $email_id, 1);
                }

                $final_body = quoted_printable_decode($final_body);
                $final_body = str_replace('=', '', $final_body);

                $received_datetime = new DateTime($overview[0]->date, new DateTimeZone('UTC'));
                $received_datetime->setTimezone(new DateTimeZone('Europe/Oslo'));

                preg_match('/\<(.*?)\>/', $overview[0]->from, $matches);
                $sender_email = $matches[1] ?? $overview[0]->from;

                $emails[] = array(
                    'subject' => mb_decode_mimeheader($overview[0]->subject),
                    'body' => decode_base64_if_needed($final_body),
                    'category' => $account['category'],
                    'received_date' => $received_datetime->format('Y-m-d'),
                    'received_time' => $received_datetime->format('H:i'),
                    'sender_email' => $sender_email,
                    'sender_ip' => $sender_ip,
                );
            }
        }
        imap_close($inbox);
    }

    return $emails;
}

function email_to_post_importer_schedule_cron() {
    if (!wp_next_scheduled('email_to_post_importer_import_hook')) {
        wp_schedule_event(time(), 'minutes_5', 'email_to_post_importer_import_hook');
    }
}

add_action('wp', 'email_to_post_importer_schedule_cron');
add_action('email_to_post_importer_import_hook', 'email_to_post_importer_import_emails');

i will be back to help you with this

Based on the symptoms you’ve described:

  1. Locked Emails in Outlook: When using IMAP (which you are), marking emails as read, moving, deleting, or making any changes in one client (like your PHP script) is often immediately reflected in all other email clients accessing that account. This is a feature of IMAP. If an email is being accessed or modified simultaneously by two sources (like your PHP script and Outlook), there could be issues like the ones you described.

  2. Some Emails Not Imported: If some emails from the same sender are imported, but others aren’t, you may want to check if there’s something different about those specific emails. Maybe they have larger attachments, maybe they are formatted differently, or maybe there’s something else unique about them.

Here are some steps you can take to diagnose and potentially fix the problem:

  1. Error Logging: Even if you don’t see any error messages, it’s possible there were errors that just weren’t displayed or logged.

You can try adding error logging to your script:

error_reporting(E_ALL);
ini_set('log_errors', '1');
ini_set('error_log', '/path/to/your/custom/php/error_log.txt');

After adding this, any errors should be written to error_log.txt. This could help you diagnose issues.

  1. Debugging: You can add var_dump() or error_log() calls after significant operations in your script to see the state of your variables or to check if a certain line of code is being executed.

  2. Modify Email Status Only After Success: Instead of marking an email as read when you fetch it, you could mark it as read only after you’ve successfully processed it. This way, if there’s an error while processing, the email remains unread and can be tried again later.

  3. Check Email Size or Attachments: If only some emails aren’t being imported, they might be too large or have large attachments. Adjust your PHP’s memory_limit and max_execution_time to handle larger emails or attachments.

  4. Thoroughly Review the Email Content: Make sure there isn’t anything in the problematic emails that could be causing issues, such as unusual characters or formats.

  5. Concurrent Access Issues: Ensure that your script and Outlook (or any other email client) aren’t accessing the email account at the same time. This can cause unexpected behavior.

  6. Server-Side Restrictions: Some email servers might have rate limits or other restrictions on how often you can connect or how many emails you can fetch in a given timeframe. Ensure you’re not hitting those limits.

  7. Use a Dedicated Email Account: If possible, consider using a dedicated email account for this import process. That way, there won’t be conflicts with other software or users accessing the account simultaneously.

Please remember, email servers can be finicky, and depending on the provider, the behavior can vary. Always ensure you’re respecting the terms of service and rate limits, especially when accessing the server programmatically.

Sponsor our Newsletter | Privacy Policy | Terms of Service