Search code examples
phpemailpear

Using Pear Mail to send plain text and html emails (How to set "Content-Type" and use boundary properly)


I'm trying to develop a function for sending email that can be used in various parts of my site. I want emails to be SMTP Authenticated, so I'm using Pear.

A parameter of my function is set to determine if the email should be plain text, html, or sent as both (multipart/alternative)....

    if($set_content_type == 'text'){
        $content_type = 'text/plain';
    } elseif($set_content_type == 'html'){
        $content_type = 'text/html';
    } elseif($set_content_type == 'html_and_text'){
        $boundary = uniqid();
        $content_type = 'multipart/alternative; boundary=' . $boundary;
    }

I then use Mail_mime to send the email...

    $mime = new Mail_mime();
    $mime->setHTMLBody($html);
    $mime->setTXTBody($text);
    $body = $mime->get();

    $host = "myhost";
    $port = "25"; // 8025, 587 and 25 can also be used.

    $username = "myusername";
    $password = "mypassword";

    $headers = array (
        'From' => $from,
        'To' => $to,
        'Subject' => $subject,
        'Content-Type:' => $content_type);

    $headers = $mime->headers($headers);
    $smtp = Mail::factory('smtp',
    array ('host' => $host,
        'port' => $port,
        'auth' => true,
        'username' => $username,
        'password' => $password));

    $mail = $smtp->send($to, $headers, $body);  

My question/problem: Where in this code can I set the parts of the message to obey the multipart/alternative mime type and use the boundary properly like what's shown in this answer (Different Content Types in email)?


Solution

  • You have to set the ContentType on your $mime object

    $mime = new Mail_mime();
    $mime->setHTMLBody($html);
    $mime->setTXTBody($text);
    $mime->setContentType($content_type);
    $body = $mime->get();
    

    Now I suggest you to use another mailer than one coming from pear. Pear is a bit an old packet manager and some application stop supporting it like PHPUnit and Symfony.

    It's better to use another one which could be installed via composer. You can have a look after Swiftmailer