Send email with a template using php
How can I send an email using PHP then add a template design in the email? I’m using this:
$to = "someone@example.com"; $subject = "Test mail"; $message = "Hello! This is a simple email message."; $from = "someonelse@example.com"; $headers = "From: $from"; mail($to,$subject,$message,$headers); echo "Mail Sent.";
And it works fine! The problem is just how to add a template.
Why not try something as simple as this :
$variables = array(); $variables['name'] = "Robert"; $variables['age'] = "30"; $template = file_get_contents("template.html"); foreach($variables as $key => $value) < $template = str_replace('>', $value, $template); > echo $template;
Your template file being something like :
Lets have a small crack at this 🙂
class Emailer < var $recipients = array(); var $EmailTemplate; var $EmailContents; public function __construct($to = false) < if($to !== false) < if(is_array($to)) < foreach($to as $_to)< $this->recipients[$_to] = $_to; > >else < $this->recipients[$to] = $to; //1 Recip > > > function SetTemplate(EmailTemplate $EmailTemplate) < $this->EmailTemplate = $EmailTemplate; > function send() < $this->EmailTemplate->compile(); //your email send code. > >
Notice the function SetTemplate() .
Heres a a small template class
class EmailTemplate < var $variables = array(); var $path_to_file= array(); function __construct($path_to_file) < if(!file_exists($path_to_file)) < trigger_error('Template File not found!',E_USER_ERROR); return; >$this->path_to_file = $path_to_file; > public function __set($key,$val) < $this->variables[$key] = $val; > public function compile() < ob_start(); extract($this->variables); include $this->path_to_file; $content = ob_get_contents(); ob_end_clean(); return $content; > >
Here’s a small example, you still need to do the core of the script but this will provide you with a nice layout to get started with.
$emails = array( 'bob@bobsite.com', 'you@yoursite.com' ); $Emailer = new Emailer($emails); //More code here $Template = new EmailTemplate('path/to/my/email/template'); $Template->Firstname = 'Robert'; $Template->Lastname = 'Pitt'; $Template->LoginUrl= 'http://stackoverflow.com/questions/3706855/send-email-with-a-template-using-php'; //. $Emailer->SetTemplate($Template); //Email runs the compile $Emailer->send();
Thats really all there is to it, just have to know how to use objects and its pretty simple from there, ooh and the template would look a little something like this:
Welcome to my site, Dear , You have been registered on our site. Please visit ">This Link to view your upvotes Regards.
$value) < $template = str_replace('>', $value, $template); > return $template; > > ?>
Name: > Email: > subject: > ------messages------ > ---------------------
$name, 'email' => $from, 'subject' => $subject, 'messages' => $message)); echo ''; echo $text; echo ''; $mail = @mail($to, $subject, $text, $headers); if($mail) < echo "Mail Sent.
"; > else < echo "Mail Fault.
"; > ?>
$message_to_client = file_get_contents("client_email.html"); //$message_to_client = "bla bla > bla bla"; $variables = array( 'SITE_TITLE' => $SITE_TITLE, 'SITE_LOGO' => $SITE_LOGO, 'SITE_URL' => $SITE_URL, 'CLIENT_NAME' => strip_tags($data->clientname), 'PHONE' => strip_tags($data->phone), 'EMAIL' => strip_tags($data->email), 'CITY' => strip_tags($data->city), 'REGION' => strip_tags($data->region), 'COMMENT' => htmlentities($data->comment) ); $message_to_client = preg_replace_callback('/<<([a-zA-Z0-9\_\-]*?)>>/i', function($match) use ($variables) < return $variables[$match[1]]; >, $message_to_client );
PHP mail() Function
Example
// the message
$msg = "First line of text\nSecond line of text";
?php>
// use wordwrap() if lines are longer than 70 characters
$msg = wordwrap($msg,70);
// send email
mail("someone@example.com","My subject",$msg);
?>
Definition and Usage
The mail() function allows you to send emails directly from a script.
Syntax
Parameter Values
Parameter | Description |
---|---|
to | Required. Specifies the receiver / receivers of the email |
subject | Required. Specifies the subject of the email. Note: This parameter cannot contain any newline characters |
message | Required. Defines the message to be sent. Each line should be separated with a LF (\n). Lines should not exceed 70 characters. |
Windows note: If a full stop is found on the beginning of a line in the message, it might be removed. To solve this problem, replace the full stop with a double dot:
$txt = str_replace("\n.", "\n..", $txt);
?>
Note: When sending an email, it must contain a From header. This can be set with this parameter or in the php.ini file.
Technical Details
Return Value: | Returns the hash value of the address parameter, or FALSE on failure. Note: Keep in mind that even if the email was accepted for delivery, it does NOT mean the email is actually sent and received! |
---|---|
PHP Version: | 4+ |
PHP Changelog: | PHP 7.2: The headers parameter also accepts an array PHP 5.4: Added header injection protection for the headers parameter. PHP 4.3.0: (Windows only) All custom headers (like From, Cc, Bcc and Date) are supported, and are not case-sensitive. PHP 4.2.3: The parameter parameter is disabled in safe mode PHP 4.0.5: The parameter parameter was added |
More Examples
Send an email with extra headers:
$to = "somebody@example.com";
$subject = "My subject";
$txt = "Hello world!";
$headers = "From: webmaster@example.com" . "\r\n" .
"CC: somebodyelse@example.com";
?php>
$to = "somebody@example.com, somebodyelse@example.com";
$subject = "HTML email";
?php>
$message = "
This email contains HTML Tags!
Firstname | Lastname |
---|---|
John | Doe |
";
// Always set content-type when sending HTML email
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
// More headers
$headers .= 'From: ' . "\r\n";
$headers .= 'Cc: myboss@example.com' . "\r\n";
Php send email based on html template Code Example, send email using php mailer example; send email template php; send email template with mail message body in custom php; Send email with a template using php; php html mail template; php create email; how we show own template in mail in php; create php link with email informaiton; Which email template is best for …
PHP - Sending Emails using PHP
PHP must be configured correctly in the php.ini file with the details of how your system sends email. Open php.ini file available in /etc/ directory and find the section headed [mail function] .
Windows users should ensure that two directives are supplied. The first is called SMTP that defines your email server address. The second is called sendmail_from which defines your own email address.
The configuration for Windows should look something like this −
[mail function] ; For Win32 only. SMTP = smtp.secureserver.net ; For win32 only sendmail_from = webmaster@tutorialspoint.com
Linux users simply need to let PHP know the location of their sendmail application. The path and any desired switches should be specified to the sendmail_path directive.
The configuration for Linux should look something like this −
[mail function] ; For Win32 only. SMTP = ; For win32 only sendmail_from = ; For Unix only sendmail_path = /usr/sbin/sendmail -t -i
Sending plain text email
PHP makes use of mail() function to send an email. This function requires three mandatory arguments that specify the recipient's email address, the subject of the the message and the actual message additionally there are other two optional parameters.
mail( to, subject, message, headers, parameters );
Here is the description for each parameters.
Required. Specifies the receiver / receivers of the email
Required. Specifies the subject of the email. This parameter cannot contain any newline characters
Required. Defines the message to be sent. Each line should be separated with a LF (\n). Lines should not exceed 70 characters
Optional. Specifies additional headers, like From, Cc, and Bcc. The additional headers should be separated with a CRLF (\r\n)
Optional. Specifies an additional parameter to the send mail program
As soon as the mail function is called PHP will attempt to send the email then it will return true if successful or false if it is failed.
Multiple recipients can be specified as the first argument to the mail() function in a comma separated list.
Sending HTML email
When you send a text message using PHP then all the content will be treated as simple text. Even if you will include HTML tags in a text message, it will be displayed as simple text and HTML tags will not be formatted according to HTML syntax. But PHP provides option to send an HTML message as actual HTML message.
While sending an email message you can specify a Mime version, content type and character set to send an HTML email.
Example
Following example will send an HTML email message to xyz@somedomain.com copying it to afgh@somedomain.com. You can code this program in such a way that it should receive all content from the user and then it should send an email.
This is HTML message."; $message .= "This is headline.
"; $header = "From:abc@somedomain.com \r\n"; $header .= "Cc:afgh@somedomain.com \r\n"; $header .= "MIME-Version: 1.0\r\n"; $header .= "Content-type: text/html\r\n"; $retval = mail ($to,$subject,$message,$header); if( $retval == true ) < echo "Message sent successfully. "; >else < echo "Message could not be sent. "; >?>
Sending attachments with email
To send an email with mixed content requires to set Content-type header to multipart/mixed . Then text and attachment sections can be specified within boundaries .
A boundary is started with two hyphens followed by a unique number which can not appear in the message part of the email. A PHP function md5() is used to create a 32 digit hexadecimal number to create unique number. A final boundary denoting the email's final section must also end with two hyphens.
x"; $headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"\""; $email_txt .= $msg_txt; $email_message .= "This is a multi-part message in MIME format.\n\n" . "--\n" . "Content-Type:text/html; charset = \"iso-8859-1\"\n" . "Content-Transfer-Encoding: 7bit\n\n" . $email_txt . "\n\n"; $data = chunk_split(base64_encode($data)); $email_message .= "--\n" . "Content-Type: ;\n" . " name = \"\"\n" . //"Content-Disposition: attachment;\n" . //" filename = \"\"\n" . "Content-Transfer-Encoding: base64\n\n" . $data . "\n\n" . "----\n"; $ok = mail($email_to, $email_subject, $email_message, $headers); if($ok) < echo "File Sent Successfully."; unlink($attachment); // delete a file after attachment sent. >else < die("Sorry but the email could not be sent. Please go back and try again!"); >> move_uploaded_file($_FILES["filea"]["tmp_name"], 'temp/'.basename($_FILES['filea']['name'])); mail_attachment("$from", "youremailaddress@gmail.com", "subject", "message", ("temp/".$_FILES["filea"]["name"])); > ?>
Your Name: |
Your Email Address: |
Attach File: |
PHP mail() Function, PHP Version: 4+ PHP Changelog: PHP 7.2: The headers parameter also accepts an array PHP 5.4: Added header injection protection for the headers parameter. PHP 4.3.0: (Windows only) All custom headers (like From, Cc, Bcc and Date) are supported, and are not case-sensitive. PHP 4.2.3: The parameter parameter is …
Отправка почты по шаблону на PHP
Пример по созданию и отправке письма на основании шаблонов писем.
// Подключаем функции. include_once "lib/mailx.php"; include_once "lib/mailenc.php"; $text = "Well, now, ain't this a surprise?"; $tos = array("Пупкин Василий , Иванов "); $tpl = file_get_contents("mail.eml"); foreach ($tos as $to) < $mail = $tpl; $mail = strtr($mail, array( "" => $to, "" => $text, )); $mail = mailenc($mail); mailx($mail); >
// Функция отправляет письмо, полностью заданное в параметре $mail. // Корректно обрабатываются заголовки To и Subject. function mailx($mail) < // Разделяем тело сообщения и заголовки. list ($head, $body) = preg_split("/\r?\n\r?\n/s", $mail, 2); // Выделяем заголовок To. $to = ""; if (preg_match('/^To:\s*([^\r\n]*)[\r\n]*/m', $head, $p)) < $to = @$p[1]; // сохраняем $head = str_replace($p[0], "", $head); // удаляем из исходной строки >// Выделяем Subject. $subject = ""; if (preg_match('/^Subject:\s*([^\r\n]*)[\r\n]*/m', $head, $p)) < $subject = @$p[1]; $head = str_replace($p[0], "", $head); >// Отправляем почту. Внимание! Опасный прием! mail($to, $subject, $body, trim($head)); >
// Корректно кодирует все заголовки в письме $mail с использованием // метода base64. Кодировка письма определяется автоматически на основе // заголовка Content-type. Возвращает полученное письмо. function mailenc($mail) < // Разделяем тело сообщения и заголовки. list ($head, $body) = preg_split("/\r?\n\r?\n/s", $mail, 2); // Определяем кодировку письма по заголовку Content-type. $encoding = ''; $re = '/^Content-type:\s*\S+\s*;\s*charset\s*=\s*(\S+)/mi'; if (preg_match($re, $head, $p)) $encoding = $p[1]; // Проходимся по всем строкам-заголовкам. $newhead = ""; foreach (preg_split('/\r?\n/s', $head) as $line) < // Кодируем очередной заголовок. $line = mailenc_header($line, $encoding); $newhead .= "$line\r\n"; >// Формируем окончательный результат. return "$newhead\r\n$body"; > // Кодирует в строке максимально возможную последовательность // символов, начинающуюся с недопустимого символа и НЕ // включающую E-mail (адреса E-mail обрамляют символами < и >). // Если в строке нет ни одного недопустимого символа, преобразование // не производится. function mailenc_header($header, $encoding) < // Кодировка не задана - делать нечего. if (!$encoding) return $header; // Сохраняем кодировку в глобальной переменной. Без использования // ООП это - единственный способ передать дополнительный параметр // callback-функции. $GLOBALS['mail_enc_header_encoding'] = $encoding; return preg_replace_callback( '/([\x7F-\xFF][^<>\r\n]*)/s', 'mailenc_header_callback', $header ); > // Служебная функция для использования в preg_replace_callback(). function mailenc_header_callback($p) < $encoding = $GLOBALS['mail_enc_header_encoding']; // Пробелы в конце оставляем незакодированными. preg_match('/^(.*?)(\s*)$/s', $p[1], $sp); return "=?$encoding?B?".base64_encode($sp[1])."?=".$sp[2]; >
mail.eml - шаблон письма
From: Почтовый робот To: Subject: Добрый день! Content-type: text/plain; charset=windows-1251 Привет, ! Это сообщение сгенерировано роботом - не отвечайте на него.
Обратите внимание на другие скрипты отправки почты: