. .

PHP: Versenden von eMails über einen (entfernten) SMTP-Server


Über fsockopen() können mit PHP TCP-Verbindungen aufgebaut werden – so auch zu einem SMTP-Dienst.
Beim Versenden von eMails müssen bei der SMTP-Sitzung natürlich bestimmte Vorgaben und Abläufe erfüllt sein (siehe auch RFC 821).

Die kleine Klasse „eMail“ ermöglicht das Versenden von eMails auf recht einfache Weise.
Allerdings ist sie an die Bedürfnisse des deutschen Zeichensatzes angepasst.

Bei der Authentifizierung sollte darauf geachtet werden, dass der SMTP-Server die Methode der Authentifzierung auch unterstützt bzw. zulässt.

Unten in diesem Beitrag ist ein Beispiel, wie dann über die Klasse „eMail“ eine HTML-eMail versendet werden kann.

 

<?PHP
/*
 * this is a small class for sending mails via smtp
 * by Hofmann R. Julian // ~ 2010
 */

if (!defined('BY_INDEX')) { exit; }

class eMail {
    var $smtpServer, $smtpPort, $smtpDomain, $smtpUser, $smtpPassword;
    var $content;
    var $encoding;
    var $htmlMailReplace;
    var $doNotLog;

    function eMail($smtpDomain = NULL, $smtpUser = NULL, $smtpPassword = NULL, $smtpServer = NULL, $smtpPort = 25) {
        $this->smtpServer = ($smtpServer) ? $smtpServer : '127.0.0.1';
        $this->smtpUser = ($smtpUser) ? $smtpUser : 'do-not-reply@localhost';
        $this->smtpPassword = ($smtpPassword) ? $smtpPassword : 'www.nyan.cat';
        $this->smtpPort = ($smtpPort) ? $smtpPort : 25;

        $this->smtpDomain = ($smtpDomain) ? $smtpDomain : 'localhost';

        $this->content = array();
        $this->content['content'] = 'text/plain';
        $this->content['enconding'] = '8bit';
        $this->content['mailer'] = 'PHP/'.(phpversion());

        $this->encoding = 'UTF-8'; // = iconv_get_encoding("input_encoding");
        $this->doNotLog = 0;

        $this->htmlMailReplace = array(
            array("\\n",  "\\r",  chr(196), chr(228), chr(214), chr(246), chr(220), chr(252), chr(223)),
            array('<br />', '',   '&Auml;', '&auml;', '&Ouml;', '&ouml;', '&Uuml;', '&uuml;', '&szlig;')
        );
    }
    function setHTML($t = 1) {
        if ($t == 1)
            $this->content['content'] = 'text/html';
        else
            $this->content['content'] = 'text/plain';
    }
    function setSubject($subject) {
        $this->content['subject'] = iconv($this->encoding, 'ISO-8859-1//IGNORE', $subject);
    }
    function setSender($sender) {
        $this->content['sender'] = $sender;
    }
    function setEncoding($encoding) {
        $this->content['encoding'] = $encoding;
    }
    function setSenderName($senderName) {
        $this->content['senderName'] = '"'.$senderName.'"';
    }
    function addRecipients($rec = NULL) {
        if (is_array($rec)) {
            foreach ($rec as $r)
                $this->content['recipients'][] = $r;
        } else
            $this->content['recipients'][] = $rec;
    }
    function addBlindCopies($rec = NULL) {
        if (is_array($rec)) {
            foreach ($rec as $r)
                $this->content['bcc'][] = $r; 
        } else
            $this->content['bcc'][] = $rec;
    }   
    function checkMailAddress($mail) {
        if (eregi('^[a-z0-9]+([-_\.]?[a-z0-9])+@[a-z0-9]+([-_\.]?[a-z0-9])+\.[a-z]{2,4}', $mail))
            return TRUE;
        else
            return FALSE;
    }   
    function displayErrors($flag = 1) {
        if ($flag == 1)
            error_reporting(E_ALL);
    }
    function send($text) {
        $this->content['text'] = ($this->content['content'] == 'text/html') ?
            iconv($this->encoding, 'ISO-8859-1//IGNORE', (str_replace(
                $this->htmlMailReplace[0], $this->htmlMailReplace[1], html_entity_decode($text)))) :
            iconv($this->encoding, 'ISO-8859-1//IGNORE', htmlentities($text));

        if ((!$this->content['sender']) || (!is_array($this->content['recipients'])))
            return FALSE;

        $from = ($this->content['senderName']) ? iconv($this->enconding, 'ISO-8859-1//IGNORE',
            $this->content['senderName'])." <{$this->content['sender']}>" : $this->content['sender'];

        $handle = fsockopen($this->smtpServer, $this->smtpPort);

        // all in one because script seems to be too fast for smtp server...

        $giveIt = 'EHLO '.$this->smtpDomain."\r\n".
            'AUTH LOGIN'."\r\n".
            base64_encode($this->smtpUser)."\r\n".
            base64_encode($this->smtpPassword)."\r\n".
            'MAIL FROM: '.$this->content['sender']."\r\n";
        foreach ($this->content['recipients'] as $recipient)
            $giveIt .= 'RCPT TO: '.$recipient."\r\n";
        $giveIt .= 'DATA'."\r\n".
            'FROM: '.$from."\r\n".
            'TO: '.(implode(',', $this->content['recipients']))."\r\n";
        if ($this->content['bcc'])
            $giveIt .= 'BCC: '.(implode(',', $this->content['bcc']))."\r\n";
        $giveIt .= 'Content-type: '.$this->content['content'].'; charset=iso-8859-1'."\r\n".
            'Content-Transfer-Encoding: '.$this->content['enconding']."\r\n".
            'X-Mailer: '.$this->content['mailer']."\r\n".
            'Subject: '.$this->content['subject']."\r\n";

        $giveIt .= "\r\n".$this->content['text']."\r\n.\r\n";

        fputs($handle, $giveIt);
        $retval = fgets($handle);

        fputs($handle, 'QUIT'."\r\n");
        fclose($handle);
    }

/*
    function logIt(&$database_connection) {
      if ($this->doNotLog <> 1) {
        if (defined('SMTP_SEND_FROM_HOST'))
            $domain = SMTP_SEND_FROM_HOST;
        else {
            $domain = explode('.', $_SERVER['SERVER_NAME']);
            $i = count($domain);
            if ($i < 2)
                return 1;
            $domain = $domain[$i - 2].'.'.$domain[$i - 1];
        }
 
        $database_connection->query("
          INSERT INTO mails_sent_by_php
          (msbp_TimeStamp, msbp_InitiatingScript, msbp_Subject, msbp_Recipients)
            VALUES ('".(time())."', '".$_SERVER['PHP_SELF']."', '".$this->content['subject']."',
          '".(implode(',', $this->content['recipients']))."')
          ");
      }
    }
*/
}
?>


Hier nun ein Beispiel, um eine HTML-eMail per SMTP zu versenden:

<?PHP

    $emailText = 'ich bin ein Test';
    $emailSubjectName = 'Gesendet mit PHP via SMTP';
    $emailRecipients = array('first@address.de', 'second@address.de');

    $email = new eMail($_smtp_domain__, $_smtp_user__, $_smtp_password__, $_smtp_server__, $_smtp_port__);

    $email->displayErrors(0);
    $email->setSender($_smtp_sender_adress__);     /* get it from config.php, or similar */
    $email->setSenderName($_smtp_sender_name__);   /* get it from config.php, or similar */
    $email->addRecipients($emailRecipients);
    $email->setSubject('Wichtig: '.$emailSubjectName);
    $email->setHTML();

    $email->send('<html><head></head><p>'.$emailText.'</p></html>');

?>

Hinterlasse eine Antwort

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind markiert *

Du kannst folgende HTML-Tags benutzen: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>