arthurakay
arthurakay

Reputation: 5651

How do you send email from IMAP account with PHP?

I'm having an issue sending email via PHP/IMAP - and I don't know if it's because:

My application opens an IMAP connection to an email account to read messages in the inbox. It does this successfully. The problem I have is that I want to send messages from this account and have them display in the outbox/sent folder.

As far as I can tell, the PHP imap_mail() function doesn't in any way hook into the IMAP stream I currently have open.

My code executes without throwing an error. However, the email never arrives to the recipient and never displays in my sent folder.

private function createHeaders() {
    return "MIME-Version: 1.0" . "\r\n" .
        "Content-type: text/html; charset=iso-8859-1" . "\r\n" .
        "From: " . $this->accountEmail . "\r\n";
}

private function notifyAdminForCompleteSet($urlToCompleteSet) {
    $message = "
        <p>
            In order to process the latest records, you must visit
            <a href='$urlToCompleteSet'>the website</a> and manually export the set.
        </p>
    ";

    try {
        imap_mail(
            $this->adminEmail,
            "Alert: Manual Export of Records Required",
            wordwrap($message, 70),
            $this->createHeaders()
        );
        echo("   ---> Admin notified via email!\n");
    }
    catch (Exception $e) {
        throw new Exception("Error in notifyAdminForCompleteSet()");
    }
}

I'm guessing I need to copy the message into the IMAP account manually... or is there a different solution to this problem?

Also, does it matter if the domain in the "from" address is different than that of the server on whicn this script is running? I can't explain why the message is never sent.

Upvotes: 5

Views: 27742

Answers (3)

namezero
namezero

Reputation: 2293

It's been a while, but for the records for others you can get the IMAP erorr via imap_last_error(). This will give you an error string of what the last issue was.

Upvotes: 1

webbiedave
webbiedave

Reputation: 48897

imap_mail is just a wrapper to the sendmail binary like the mail function. You're better of sending the mail through normal SMTP means (take a look at PHPMailer or Swift Mailer) and then have your code place the message into the Sent folder with imap_append.

Not sure what is making the send fail but you should check the boolean return value of imap_send in your code. Beyond that, you'll want to examine your SMTP server logs for any clues.

Upvotes: 5

Oswald
Oswald

Reputation: 31637

Check the return value of your call to imap_mail. imap_mail does not throw na exception on failure, it returns false.

Also, you will have to copy the message to the sent-folder yourself, imap_mail does not do that for you.

Upvotes: 0

Related Questions