multple file attachment in mail with php [duplicate] - php

This question already has answers here:
Error with PHP mail(): Multiple or malformed newlines found in additional_header
(10 answers)
Closed 4 years ago.
I have below code for mail attachment, but it is not working, dont know why it is happening..
function mail_attachment($filename, $path, $mailto, $from_mail, $subject, $message){
$uid = md5(uniqid(time()));
$mime_boundary = "==Multipart_Boundary_x{$uid}x";
$header = "From: <".$from_mail.">\r\n";
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-Type: multipart/mixed; boundary=\"".$mime_boundary."\"\r\n\r\n";
$header .= "This is a multi-part message in MIME format.\r\n";
$header .= "--".$mime_boundary."\r\n";
$header .= "Content-type:text/html; charset=iso-8859-1\r\n";
$header .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
$header .= nl2br($message)."\r\n\r\n";
$header .= "--".$mime_boundary."\r\n";
foreach($filename as $k=>$v){
$file = $path.$v;
$file_size = filesize($file);
$handle = fopen($file, "r");
$content = fread($handle, $file_size);
fclose($handle);
$content = chunk_split(base64_encode($content));
$header .= "Content-Type: application/octet-stream; name=\"".$v."\"\r\n"; // use different content types here
$header .= "Content-Transfer-Encoding: base64\r\n";
$header .= "Content-Disposition: attachment; filename=\"".$v."\"\r\n\r\n";
$header .= $content."\r\n\r\n";
$header .= "--".$mime_boundary."--"."\r\n";
}
if (mail($mailto, $subject, "", $header)) {
//echo "mail send ... OK"; // or use booleans here
return true;
} else {
//echo "mail send ... ERROR!";
return false;
}
}
$path='upload/';
$send_email = mail_attachment($files, $path, $to, "roxmorphy26#gmail", $subject, $message);
//mail($to,$subject,$message,$headers);
if($send_email){ echo 'done';} else {echo 'not';}
but it gives error like -- Warning: mail(): Multiple or malformed newlines found in additional_header
please help.

<?php
define("LIBR", "\n"); // use a "\r\n" if you have problems
define("PRIORITY", 3); // 3 = normal, 2 = high, 4 = low
define("TRANS_ENC", "7bit");
define("ENCODING", "iso-8859-1");
class attach_mailer {
var $from_name;
var $from_mail;
var $mail_to;
var $mail_cc;
var $mail_bcc;
var $webmaster_email = "webmaster#yourdomain.com";
var $mail_headers;
var $mail_subject;
var $text_body = "";
var $html_body = "";
var $valid_mail_adresses; // boolean is true if all mail(to) adresses are valid
var $uid; // the unique value for the mail boundry
var $alternative_uid; // the unique value for the mail boundry
var $related_uid; // the unique value for the mail boundry
var $html_images = array();
var $att_files = array();
var $msg = array();
// functions inside this constructor
// - validation of e-mail adresses
// - setting mail variables
// - setting boolean $valid_mail_adresses
function attach_mailer($name = "", $from, $to, $cc = "", $bcc = "", $subject = "") {
$this->valid_mail_adresses = true;
if (!$this->check_mail_address($to)) {
$this->msg[] = "Error, the \"mailto\" address is empty or not valid.";
$this->valid_mail_adresses = false;
}
if (!$this->check_mail_address($from)) {
$this->msg[] = "Error, the \"from\" address is empty or not valid.";
$this->valid_mail_adresses = false;
}
if ($cc != "") {
if (!$this->check_mail_address($cc)) {
$this->msg[] = "Error, the \"Cc\" address is not valid.";
$this->valid_mail_adresses = false;
}
}
if ($bcc != "") {
if (!$this->check_mail_address($bcc)) {
$this->msg[] = "Error, the \"Bcc\" address is not valid.";
$this->valid_mail_adresses = false;
}
}
if ($this->valid_mail_adresses) {
$this->from_name = $this->strip_line_breaks($name);
$this->from_mail = $this->strip_line_breaks($from);
$this->mail_to = $this->strip_line_breaks($to);
$this->mail_cc = $this->strip_line_breaks($cc);
$this->mail_bcc = $this->strip_line_breaks($bcc);
$this->mail_subject = $this->strip_line_breaks($subject);
} else {
return;
}
}
function get_msg_str() {
$messages = "";
foreach($this->msg as $val) {
$messages .= $val."<br />\n";
}
return $messages;
}
// use this to prent formmail spamming
function strip_line_breaks($val) {
$val = preg_replace("/([\r\n])/", "", $val);
return $val;
}
function check_mail_address($mail_address) {
$pattern = "/^[\w-]+(\.[\w-]+)*#([0-9a-z][0-9a-z-]*[0-9a-z]\.)+([a-z]{2,4})$/i";
if (preg_match($pattern, $mail_address)) {
if (function_exists("checkdnsrr")) {
$parts = explode("#", $mail_address);
if (checkdnsrr($parts[1], "MX")){
return true;
} else {
return false;
}
} else {
// on windows hosts is only a limited e-mail address validation possible
return true;
}
} else {
return false;
}
}
function get_file_data($filepath) {
if (file_exists($filepath)) {
if (!$str = file_get_contents($filepath)) {
$this->msg[] = "Error while opening attachment \"".basename($filepath)."\"";
} else {
return $str;
}
} else {
$this->msg[] = "Error, the file \"".basename($filepath)."\" does not exist.";
return;
}
}
// use for $dispo "attachment" or "inline" (f.e. example images inside a html mail
function add_attach_file($file, $encoding = "base64", $dispo = "attachment", $type = "application/octet-stream") {
$file_str = $this->get_file_data($file);
if ($file_str == "") {
return;
} else {
if ($encoding == "base64") $file_str = base64_encode($file_str);
$this->att_files[] = array(
"data"=>chunk_split($file_str),
"name"=>basename($file),
"cont_type"=>$type,
"trans_enc"=>$encoding,
"disposition"=>$dispo);
}
}
function add_html_image($img_name) {
$file_str = $this->get_file_data($img_name);
$img_dim = getimagesize($img_name);
if ($file_str == "") {
return;
} else {
$this->html_images[] = array(
"data"=>chunk_split(base64_encode($file_str)),
"name"=>basename($img_name),
"cont_type"=>$img_dim['mime'],
"cid"=>md5(uniqid(time()))."#".$_SERVER['SERVER_NAME']);
}
}
function create_stand_headers() {
if ($this->from_name != "") {
$headers = "From: ".$this->from_name." <".$this->from_mail.">".LIBR;
$headers .= "Reply-To: ".$this->from_name." <".$this->from_mail.">".LIBR;
} else {
$headers = "From: ".$this->from_mail.LIBR;
$headers .= "Reply-To: ".$this->from_mail.LIBR;
}
if ($this->mail_cc != "") $headers .= "Cc: ".$this->mail_cc.LIBR;
if ($this->mail_bcc != "") $headers .= "Bcc: ".$this->mail_bcc.LIBR;
$headers .= sprintf("Message-ID: <%s#%s>%s", md5(uniqid(time())), $_SERVER['SERVER_NAME'], LIBR);
$headers .= "X-Priority: ".PRIORITY.LIBR;
$headers .= "X-Mailer: Attachment Mailer [version 1.2]".LIBR;
$headers .= "MIME-Version: 1.0".LIBR;
return $headers;
}
function create_html_image($img_array) {
$img = "Content-Type: ".$img_array['cont_type'].";".LIBR.chr(9)." name=\"".$img_array['name']."\"".LIBR;
$img .= "Content-Transfer-Encoding: base64".LIBR;
$img .= "Content-ID: <image".$img_array['cid'].">".LIBR;
$img .= "Content-Disposition: inline;".LIBR.chr(9)." filename=\"".$img_array['name']."\"".LIBR.LIBR;
$img .= $img_array['data'];
return $img;
}
function create_attachment($data_array) {
$att = "Content-Type: ".$data_array['cont_type'].";".LIBR.chr(9)." name=\"".$data_array['name']."\"".LIBR;
$att .= "Content-Transfer-Encoding: ".$data_array['trans_enc'].LIBR;
$att .= "Content-Disposition: ".$data_array['disposition'].";".LIBR.chr(9)." filename=\"".$data_array['name']."\"".LIBR.LIBR;
$att .= $data_array['data'];
return $att;
}
function create_html_body() {
$html = "Content-Type: text/html; charset=".ENCODING.LIBR;
$html .= "Content-Transfer-Encoding: ".TRANS_ENC.LIBR.LIBR;
foreach ($this->html_images as $img) {
$this->html_body = str_replace($img['name'], "cid:image".$img['cid'], $this->html_body);
}
$html .= $this->html_body;
return $html.LIBR.LIBR;
}
function build_message() {
$this->headers = $this->create_stand_headers();
$msg = "";
$is_html = ($this->html_body != "") ? true : false;
$is_attachment = (count($this->att_files) > 0) ? true : false;
$is_images = (count($this->html_images) > 0) ? true : false;
if ($is_attachment) {
$this->uid = md5(uniqid(time()));
$this->headers .= "Content-Type: multipart/mixed;".LIBR.chr(9)." boundary=\"".$this->uid."\"".LIBR.LIBR;
$this->headers .= "This is a multi-part message in MIME format.".LIBR;
if (!$is_html) {
$msg .= "--".$this->uid.LIBR;
} else {
$this->headers .= "--".$this->uid.LIBR;
}
}
if ($is_html) {
$this->alternative_uid = md5(uniqid(time()));
$this->headers .= "Content-Type: multipart/alternative;".LIBR.chr(9)." boundary=\"".$this->alternative_uid."\"".LIBR.LIBR;
if (!$is_attachment) {
$this->headers .= "This is a multi-part message in MIME format.".LIBR;
}
$msg .= LIBR."--".$this->alternative_uid.LIBR;
}
$body_head = "Content-Type: text/plain; charset=".ENCODING."; format=flowed".LIBR;
$body_head .= "Content-Transfer-Encoding: ".TRANS_ENC.LIBR.LIBR;
if (!$is_attachment && !$is_html) {
$this->headers .= $body_head;
} else {
$msg .= $body_head;
}
$msg .= trim($this->text_body).LIBR.LIBR;
if ($is_html) {
$msg .= "--".$this->alternative_uid.LIBR;
if ($is_images) {
$this->related_uid = md5(uniqid(time()));
$msg .= "Content-Type: multipart/related;".LIBR.chr(9)." boundary=\"".$this->related_uid."\"".LIBR.LIBR.LIBR;
$msg .= "--".$this->related_uid.LIBR;
$msg .= $this->create_html_body();
foreach ($this->html_images as $img) {
$msg .= "--".$this->related_uid.LIBR;
$msg .= $this->create_html_image($img);
}
$msg .= LIBR."--".$this->related_uid."--";
} else {
$msg .= $this->create_html_body();
}
$msg .= LIBR.LIBR."--".$this->alternative_uid."--".LIBR.LIBR;
}
if ($is_attachment) {
foreach ($this->att_files as $att) {
$msg .= "--".$this->uid.LIBR;
$msg .= $this->create_attachment($att);
}
$msg .= "--".$this->uid."--";
}
return $msg;
}
function process_mail() {
if (!$this->valid_mail_adresses) return;
if (mail($this->mail_to, $this->mail_subject, $this->build_message(), $this->headers, "-f".$this->webmaster_email)) {
$this->msg[] = "Your mail is succesfully submitted.";
return true;
} else {
$this->msg[] = "Error while sending you mail.";
return false;
}
}
}
$test = new attach_mailer($name = "Olaf", $from = "youremail#gmail.com", $to = "toemail#gmail.com", $cc = "", $bcc = "", $subject = "Test text email with attachments");
$test->text_body = "...Some body text\n\n the admin";
$test->add_attach_file("uploads/admin_doc.docx");
//$test->add_attach_file("ip2nation.zip");
$test->process_mail();
echo $test->get_msg_str();

Related

UPLOAD has a deprecated constructor [duplicate]

This question already has answers here:
Severity: 8192 Message: Methods with the same name as their class will not be constructors in a future version of PHP;
(6 answers)
Closed 9 days ago.
I have a script that sends a SMS alert but it is failing on "class UPLOAD". The PHP error log shows "Methods with the same name as their class will not be constructors in a future version of PHP; UPLOAD has a deprecated constructor". Can anyone see what is going wrong.
class UPLOAD
{
var $URI='';
var $Host='localhost';
var $Port='80';
var $Fields=array();
var $Files=array();
var $Headers=array();
var $Request='';
var $RequestHeaders='';
var $RequestBody='';
var $Response='';
var $ResponseHeaders='';
var $ResponseBody='';
var $log='';
var $errors=array();
var $UseProxy=false;
var $ProxyHost='localhost';
var $ProxyPort=3128;
// constructor
function UPLOAD($URI)
{
$this->log .= 'Creating object with URI: '.htmlspecialchars($URI)."\n";
if (preg_match("/^https:\/\/([^\/:]+)[:]?(\d*)?(.*)/i", $URI, $m))
{
$this->URI = $URI;
$this->Host = $m[1];
$this->Port = ((int)$m[2])==0 ? 80 : (int)$m[2];
$this->log .= 'Object with URI '.htmlspecialchars($URI)." created.\n";
$this->log .= ' host: '.htmlspecialchars($this->Host)."\n";
$this->log .= ' port: '.htmlspecialchars($this->Port)."\n";
}
else
{
$this->log .= 'Object with URI '.htmlspecialchars($URI)." create failed.\n";
$this->errors[] = 'Access URI '.htmlspecialchars('"'.$URI.'"').' is not valid';
}
}
// adding field(s) to form
function SetFields($field, $value='')
{
if (is_array($field))
{
foreach($field as $k=>$v)
{
$this->SetFields($k, $v);
}
}
else
{
$this->Fields[] = array($field, $value);
$this->log .= 'Added field '.htmlspecialchars('"'.$field.'"').' with value '.htmlspecialchars('"'.$value.'"')."\n";
}
}
// adding files to form
function SetFiles($field, $filename='', $content='')
{
if (is_array($field))
{
foreach($field as $k=>$v)
{
$this->SetFiles($k, $v);
}
}
else
{
if (is_array($filename))
{
foreach($filename as $k=>$v)
{
$this->SetFiles($field, $k, $v);
}
}
else
{
$this->Files[] = array($field, $filename, $content);
$this->log .= 'Added field '.htmlspecialchars('"'.$field.'"').' of type file with name '.htmlspecialchars('"'.$filename.'"')."\n";
}
}
}
// send form
function Send()
{
if (!$hosts=gethostbynamel($this->Host))
{
$this->errors[] = 'Send failed. Host '.htmlspecialchars('"'.$this->Host.'"').' not found.';
return false;
}
$fp = #fsockopen($this->Host, $this->Port, $errno, $errstr, 3);
if (!$fp)
{
$this->errors[] = "Connection failed with: ".$errno.' '.htmlspecialchars($errstr);
return false;
}
$this->calculate();
$out = $this->Request;
fwrite($fp, $out, strlen($out));
$result = '';
while (!feof($fp)) {
$result .= fgets($fp, 1024);
}
$this->Response = $result;
$i = strpos($result, "\r\n\r\n");
if ($i>0)
{
$this->ResponseHeader = substr($result, 0, $i);
$this->ResponseBody = substr($result, $i+4);
}
else
{
$this->ResponseHeader = $result;
$this->ResponseBody = '';
}
return true;
}
// calculate form
function calculate()
{
$boundary = '---------------------------PHPUPLOADCLASS';
$body = '';
foreach($this->Fields as $k=>$v)
{
$body .= "--$boundary\r\n";
$body .= 'Content-Disposition: form-data; name="'.$v[0]."\"\r\n";
$body .= "\r\n".$v[1]."\r\n";
}
foreach($this->Files as $k=>$v)
{
$body .= "--$boundary\r\n";
$body .= 'Content-Disposition: form-data; name="'.$v[0].'"; filename="'.$v[1]."\"\r\n";
$body .= "Content-Type: application/octet-stream\r\n";
$body .= "\r\n".$v[2]."\r\n";
}
$body .= "--$boundary--\r\n";
$headers = 'POST '.$this->URI." HTTPS/1.0\r\n";
$headers .= 'Host: '.$this->Host."\r\n";
$headers .= "User-Agent: Mozilla/4.0 (PHP Uploader Class)\r\n";
$headers .= "Accept: */*\r\n";
$headers .= "Pragma: no-cache\r\n";
foreach($this->Headers as $k=>$v)
{
$headers .= $k.': '.$v."\r\n";
}
$headers .= "Content-Type: multipart/form-data; boundary=$boundary\r\n";
$headers .= "Content-Length: ".strlen($body)."\r\n";
$headers .= "Connection: Close\r\n\r\n";
$this->Request = $headers.$body;
$this->RequestHeaders = $headers;
$this->RequestBody = $body;
}
}
[/CODE]
In PHP 7 the old style of constructor having the same name of the class name is deprecated.
So you need to use other name of method which is not same as class
name.
Or you can use A magic method in PHP that usually starts with 2 underscores instead of function UPLOAD.
Like:
public function __construct()
{
//put all your logic to instantiate an object with class properties
}
instead of :
public function UPLOAD()
{
//put all your logic to instantiate an object with class properties
}

Php-imap_open-How can I show a link to save attachment, without save files on server?

I tried to fetchbody to read emails from imap_open connection.
I can read the text of the mail and I can save all attachments on my Webserver.
But I want to create a link for everyone attachment-file, to download the files directly from the mail-Server, without save files on my Webserver.
I want:
Link—>Download—>direct from Mail-Server
At this moment:
Save all attachments on my Webserver—> link to each file on my Webserver—> Download attachments from my Webserver
<?php
If ((Isset($_POST['uid']) == false) or (Isset($_POST['user']) == false) or (Isset($_POST['pw']) == false)) {
echo ("Keine Zuordnung vorhanden");
return;
}
function getAttachments($imap, $mailNum, $part, $partNum) {
$attachments = array();
if (isset($part->parts)) {
foreach ($part->parts as $key => $subpart) {
if($partNum != "") {
$newPartNum = $partNum . "." . ($key + 1);
}
else {
$newPartNum = ($key+1);
}
$result = getAttachments($imap, $mailNum, $subpart,
$newPartNum);
if (count($result) != 0) {
array_push($attachments, $result);
}
}
}
else if (isset($part->disposition)) {
// print_r($part);
if (strtoupper($part->disposition) == "ATTACHMENT") {
$partStruct = imap_bodystruct($imap, $mailNum, $partNum);
$attachmentDetails = array(
"name" => $part->dparameters[0]->value,
"subtype" => $partStruct->subtype,
"partNum" => $partNum,
"enc" => $partStruct->encoding
);
return $attachmentDetails;
}
}
return $attachments;
}
function getPartList($struct, $base="") {
$res=Array();
if (!property_exists($struct,"parts")) {
return [$base?:"0"];
} else {
$num=1;
if (count($struct->parts)==1) return getPartList($struct->parts[0], $base);
foreach ($struct->parts as $p=>$part) {
foreach (getPartList($part, $p+1) as $subpart) {
$res[]=($base?"$base.":"").$subpart;
}
}
}
return $res;
}
$username = $_POST['user'] ;
$pw = $_POST['pw'];
$server_in = $_POST['server'];
$port = $_POST['port'];
$uid = $_POST['uid'];
$msgno = $_POST['msgno'];
$imap= imap_open($server_in, $username, $pw);
$msgno = imap_msgno($imap, $uid);
$nachrichten_struktur = imap_fetchstructure($imap, $uid, FT_UID);
$kodierung = $nachrichten_struktur->encoding;
$nachrichten_type = $nachrichten_struktur->type;
$res=getPartList($nachrichten_struktur);
if ($nachrichten_type == 0){
$text = quoted_printable_decode(imap_fetchbody($imap, $msgno ,1));
}
else if ($nachrichten_type == 1){
if(count($res) <=2){
$text = quoted_printable_decode(imap_fetchbody($imap, $msgno , 2));
}
else if(count($res) >=3){
$text = quoted_printable_decode(imap_fetchbody($imap, $msgno , 2.2));
}
}
else{
$text = imap_fetchbody($imap, $msgno ,1);
}
switch ($kodierung) {
# 7BIT
case 0:
$body = $text;
# 8BIT
case 1:
$body = quoted_printable_decode(imap_8bit($text));
# BINARY
case 2:
$body = imap_binary($text);
# BASE64
case 3:
$body = imap_base64($text);
# QUOTED-PRINTABLE
case 4:
$body = quoted_printable_decode($text);
# OTHER
case 5:
$body = $text;
# UNKNOWN
default:
$body = $text;
}
//attachmentDetails
$attachments = getAttachments($imap, $msgno, $nachrichten_struktur, "");
$body .= "<br />Attachments: ";
$body .= "<ul>";
foreach ($attachments as $attachment) {
$body .= '<li>' .$attachment["name"] . "</li>";
}
$body .= "</ul>";
echo $body;
imap_close($imap);
?>
Sorry, but i hadn't soo much time last few days.
I solved my problem. The right way is:
Read Email, check attachments -> write a submit link for every attachment file, AND input hidden filed which has part_number and uid_number -> click on link, send form to php file -> php file read attachment from webserver and give it back via content type:
header("Content-Type: application/octet-stream");
header("Content-Type: application/force-download");
My read file:
....
function getAttachments($imap, $mailNum, $part, $partNum) {
$attachments = array();
if (isset($part->parts)) {
foreach ($part->parts as $key => $subpart) {
if($partNum != "") {
$newPartNum = $partNum . "." . ($key + 1);
}
else {
$newPartNum = ($key+1);
}
$result = getAttachments($imap, $mailNum, $subpart,
$newPartNum);
if (count($result) != 0) {
array_push($attachments, $result);
}
}
}
else if (isset($part->disposition)) {
// print_r($part);
if (strtoupper($part->disposition) == "ATTACHMENT") {
$partStruct = imap_bodystruct($imap, $mailNum, $partNum);
$attachmentDetails = array(
"name" => $part->dparameters[0]->value,
"subtype" => $partStruct->subtype,
"partNum" => $partNum,
"enc" => $partStruct->encoding
);
return $attachmentDetails;
}
}
return $attachments;
}
function getPartList($struct, $base="") {
$res=Array();
if (!property_exists($struct,"parts")) {
return [$base?:"0"];
} else {
$num=1;
if (count($struct->parts)==1) return getPartList($struct->parts[0], $base);
foreach ($struct->parts as $p=>$part) {
foreach (getPartList($part, $p+1) as $subpart) {
$res[]=($base?"$base.":"").$subpart;
}
}
}
return $res;
}
$imap= imap_open($server_in, $username, $pw);
$msgno = imap_msgno($imap, $uid);
$nachrichten_struktur = imap_fetchstructure($imap, $uid, FT_UID);
$kodierung = $nachrichten_struktur->encoding;
$nachrichten_type = $nachrichten_struktur->type;
$res=getPartList($nachrichten_struktur);
$subtype = $nachrichten_struktur->subtype;
if ($nachrichten_type == 0){
$text = quoted_printable_decode(imap_fetchbody($imap, $msgno ,1));
}
else if ($nachrichten_type == 1){
if(count($res) <=2){
if ($subtype == "MIXED"){
$text = quoted_printable_decode(imap_fetchbody($imap, $msgno , 1));
}
else{
$text = quoted_printable_decode(imap_fetchbody($imap, $msgno , 2));
}
}
else if(count($res) >=3){
$text = quoted_printable_decode(imap_fetchbody($imap, $msgno , 1));
}
}
else{
$text = imap_fetchbody($imap, $msgno ,1);
}
switch ($kodierung) {
# 7BIT
case 0:
$body = $text;
# 8BIT
case 1:
$body = quoted_printable_decode(imap_8bit($text));
# BINARY
case 2:
$body = imap_binary($text);
# BASE64
case 3:
$body = imap_base64($text);
# QUOTED-PRINTABLE
case 4:
$body = quoted_printable_decode($text);
# OTHER
case 5:
$body = $text;
# UNKNOWN
default:
$body = $text;
}
//attachmentDetails
$attachments = getAttachments($imap, $msgno, $nachrichten_struktur, "");
if(count($attachments) > 0){
$body .= "<br />Attachments: <br /> ";
}
foreach ($attachments as $attachment) {
$body .= "<span style='display:inline-block; margin-right:1%;'><form class='form_download_attachment' action='src/php/download_attach.php' method='POST' target='_blank'>";
$body .= "<input type='hidden' name='uid' value='".$uid."'>";
$body .= "<input type='hidden' name='data-attachment_partNum' value='".$attachment["partNum"]."'>";
$body .= "<input type='hidden' name='data-enc' value='".$attachment["enc"]."'>";
//$body .= "<input type='hidden' name='server' value='".$server_in."'>";
//$body .= "<input type='hidden' name='user' value='".$username."'>";
//$body .= "<input type='hidden' name='pw' value='".$pw."'>";
$body .= '<button type="submit" class="attachment_download btn btn-warning btn-sm" >' .$attachment["name"] . "</button>";
$body .= "</form></span>";
}
....
my download file:
...
$imap_open= imap_open($get_server_in, $get_username, $get_pw);
$msgno = imap_msgno($imap_open, $get_uid);
function downloadAttachment($imap, $uid, $partNum, $encoding) {
$partStruct = imap_bodystruct($imap, imap_msgno($imap, $uid), $partNum);
$filesize = $partStruct->bytes;
$filename = $partStruct->dparameters[0]->value;
$message = imap_fetchbody($imap, $uid, $partNum, FT_UID);
switch ($encoding) {
case 0:
case 1:
$message = imap_8bit($message);
break;
case 2:
$message = imap_binary($message);
break;
case 3:
$message = imap_base64($message);
break;
case 4:
$message = quoted_printable_decode($message);
break;
}
header("Content-Description: File Transfer");
header("Content-Type: application/octet-stream");
header("Content-Type: application/force-download");
header("Content-Type: application/download");
header("Content-Disposition: attachment; filename=" . $filename);
header("Content-Transfer-Encoding: binary");
if ($_SESSION['mobile'] != "true"){
header("Content-Length: ".$filesize);
}
header("Expires: 0");
header("Cache-Control: must-revalidate");
header("Pragma: public");
echo $message;
}
downloadAttachment($imap_open, $get_uid, $get_partNum, $get_encoding);
...
Thank for your help!

Error on sending mail with attachment using Amazon AWS and PHP

I have to send mail using Amazon AWS with PHP, I am able to send simple mail but got following Error, I used many codes get from Google but still I got the same error every time.
Fatal error: Cannot redeclare Aws\constantly() (previously declared
in /path/vendor/aws/aws-sdk-php/src/functions.php:20) in
phar:///opt/lampp/htdocs/path/amazon/aws.phar/Aws/functions.php on
line 22
Code I used:-
require_once '/mypath/vendor/autoload.php';
include_once("SESUtils.php");
$subject_str = "Some Subject";
$body_str = "<strong>Some email body</strong>";
$attachment_str = file_get_contents("mypdf_file.pdf");
//send the email
$params =
array("to" => "to#xyz.com",
"subject" => "Some subject",
"message" => "<strong>Some email body</strong>",
"from" => "from#xyz.com",
"replyTo" => "reply_to#gmail.com",
"files" =>
array(
"1" => array(
"name" => "filename1",
"filepath" => "/path/to/mypdf_file.pdf",
"mime" => "application/pdf"
),
)
);
$res = SESUtils::sendMail($params);
aws version:- 3.21.6
AND SESUtils.php
require_once('aws.phar');
use Aws\Ses\SesClient;
class SESUtils {
const version = "1.0";
const AWS_KEY = "AWS_KEY";
const AWS_SEC = "AWS_SEC";
const AWS_REGION = "us-east-1";
const MAX_ATTACHMENT_NAME_LEN = 60;
public static function sendMail($params) {
$to = self::getParam($params, 'to', true);
$subject = self::getParam($params, 'subject', true);
$body = self::getParam($params, 'message', true);
$from = self::getParam($params, 'from', true);
$replyTo = self::getParam($params, 'replyTo');
$files = self::getParam($params, 'files');
$res = new ResultHelper();
// get the client ready
$client = SesClient::factory(array(
'key' => self::AWS_KEY,
'secret' => self::AWS_SEC,
'region' => self::AWS_REGION
));
// build the message
if (is_array($to)) {
$to_str = rtrim(implode(',', $to), ',');
} else {
$to_str = $to;
}
$msg = "To: $to_str\n";
$msg .= "From: $from\n";
if ($replyTo) {
$msg .= "Reply-To: $replyTo\n";
}
// in case you have funny characters in the subject
$subject = mb_encode_mimeheader($subject, 'UTF-8');
$msg .= "Subject: $subject\n";
$msg .= "MIME-Version: 1.0\n";
$msg .= "Content-Type: multipart/mixed;\n";
$boundary = uniqid("_Part_".time(), true); //random unique string
$boundary2 = uniqid("_Part2_".time(), true); //random unique string
$msg .= " boundary=\"$boundary\"\n";
$msg .= "\n";
$msg .= "--$boundary\n";
$msg .= "Content-Type: multipart/alternative;\n";
$msg .= " boundary=\"$boundary2\"\n";
$msg .= "\n";
$msg .= "--$boundary2\n";
$msg .= "Content-Type: text/plain; charset=utf-8\n";
$msg .= "Content-Transfer-Encoding: 7bit\n";
$msg .= "\n";
$msg .= strip_tags($body); //remove any HTML tags
$msg .= "\n";
// now, the html text
$msg .= "--$boundary2\n";
$msg .= "Content-Type: text/html; charset=utf-8\n";
$msg .= "Content-Transfer-Encoding: 7bit\n";
$msg .= "\n";
$msg .= $body;
$msg .= "\n";
$msg .= "--$boundary2--\n";
// add attachments
if (is_array($files)) {
$count = count($files);
foreach ($files as $file) {
$msg .= "\n";
$msg .= "--$boundary\n";
$msg .= "Content-Transfer-Encoding: base64\n";
$clean_filename = self::clean_filename($file["name"], self::MAX_ATTACHMENT_NAME_LEN);
$msg .= "Content-Type: {$file['mime']}; name=$clean_filename;\n";
$msg .= "Content-Disposition: attachment; filename=$clean_filename;\n";
$msg .= "\n";
$msg .= base64_encode(file_get_contents($file['filepath']));
$msg .= "\n--$boundary";
}
// close email
$msg .= "--\n";
}
// now send the email out
try {
$ses_result = $client->sendRawEmail(
array(
'RawMessage' => array(
'Data' => base64_encode($msg)
)
), array(
'Source' => $from,
'Destinations' => $to_str
)
);
if ($ses_result) {
$res->message_id = $ses_result->get('MessageId');
} else {
$res->success = false;
$res->result_text = "Amazon SES did not return a MessageId";
}
} catch (Exception $e) {
$res->success = false;
$res->result_text = $e->getMessage().
" - To: $to_str, Sender: $from, Subject: $subject";
}
return $res;
}
private static function getParam($params, $param, $required = false) {
$value = isset($params[$param]) ? $params[$param] : null;
if ($required && empty($value)) {
throw new Exception('"'.$param.'" parameter is required.');
} else {
return $value;
}
}
/** Clean filename function - to be mail friendly **/
public static function clean_filename($str, $limit = 0, $replace=array(), $delimiter='-') {
if( !empty($replace) ) {
$str = str_replace((array)$replace, ' ', $str);
}
$clean = iconv('UTF-8', 'ASCII//TRANSLIT', $str);
$clean = preg_replace("/[^a-zA-Z0-9\.\/_| -]/", '', $clean);
$clean = preg_replace("/[\/| -]+/", '-', $clean);
if ($limit > 0) {
//don't truncate file extension
$arr = explode(".", $clean);
$size = count($arr);
$base = "";
$ext = "";
if ($size > 0) {
for ($i = 0; $i < $size; $i++) {
if ($i < $size - 1) { //if it's not the last item, add to $bn
$base .= $arr[$i];
//if next one isn't last, add a dot
if ($i < $size - 2)
$base .= ".";
} else {
if ($i > 0)
$ext = ".";
$ext .= $arr[$i];
}
}
}
$bn_size = mb_strlen($base);
$ex_size = mb_strlen($ext);
$bn_new = mb_substr($base, 0, $limit - $ex_size);
// doing again in case extension is long
$clean = mb_substr($bn_new.$ext, 0, $limit);
}
return $clean;
}
}
class ResultHelper {
public $success = true;
public $result_text = "";
public $message_id = "";
}
I had this error about redeclaring constantly() and the problem was resolved in our code by simply changing:
include('/PATH/TO/aws-sdk-3/aws-autoloader.php');
to
include_once('/PATH/TO/aws-sdk-3/aws-autoloader.php');
Maybe that will help you or the next person to Google this error message!
This is just namespacing. Look at the examples for reference - you need to either use the namespaced class or reference it absolutely, for example:
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
//Load composer's autoloader
require 'vendor/autoload.php';

php smtp mail function

can i have this function send email through smtp?
function send()
{
if(mail($this->to, $this->subject, $this->body, $this->headers)) return TRUE;
else return FALSE;
}
this is part of following code:
class sendMail
{
var $to;
var $cc;
var $bcc;
var $subject;
var $from;
var $headers;
var $html;
function sendMail()
{
$this->to = "test#mail.com";
#$this->to = "test#test.com";
$this->cc = NULL;
$this->bcc = NULL;
$this->subject = NULL;
$this->from = NULL;
$this->headers = NULL;
$this->html = FALSE;
}
function getParams($params)
{
$i = 0;
foreach ($params as $key => $value) {
switch($key) {
case 'Submit':
NULL;
break;
default:
if ($key == 'email')
{
$this->from = $value;
$this->subject ="Contactgegevens from " . $value . " at www.webandeve.nl ";
}
$this->body[$i]["key"] = str_replace("_", " ", ucWords(strToLower($key)));
$this->body[$i++]["value"] = $value;
}
}
}
function setHeaders()
{
$this->headers = "From: $this->from\r\n";
if($this->html === TRUE) {
$this->headers.= "MIME-Version: 1.0\r\n";
$this->headers.= "Content-type: text/html; charset=iso-8859-1\r\n";
}
}
function parseBody()
{
$count = count($this->body);
for($i = 0; $i < $count; $i++) {
if($this->html) $content.= "<b>";
$content .= $this->body[$i]["key"].': ';
if($this->html) $content.= "</b>";
if($this->html) $content .= nl2br($this->body[$i]["value"])."\n";
else $content .= $this->body[$i]["value"];
if($this->html) $content.= "<br>\n";
else $content.= "\n".str_repeat("-", 80)."\n";
}
if($this->html) {
$content = "
<style>
BODY {
font-family: verdana;
font-size: 10;
}
</style>
".$content;
}
$this->body = $content;
}
function send()
{
if(mail($this->to, $this->subject, $this->body, $this->headers)) return TRUE;
else return FALSE;
}
function set($key, $value)
{
if($value) $this->$key = $value;
else unset($this->$key);
}
function get_location()
{
return header('Location: thankyou.htm');break;
}
}
I've been looking for a simple solution but cannot find any (for my knowledge of php) but Git and some full replacements of my script.
If you want to use your SMTP mail config with the mail() function you need to set the SMTP config in your php.ini.
See E-Mail configuration for details.
However I would recommend the use of a third party lib like PHPMailer

issue with mail() in php

i am using following code, to send a mail, with two attachments,
Problems i'm having is, it takes only one attachment, i want to send to attachment in mail, and i'm not getting autoresponse,
can any one help me please, here is my code
<?php session_start();
$redirect_url = '../thanks.html';
$your_email ='name#domain.com';// <<=== update to your email address
$attachment_enabled = 1;
$autoresponder_enabled = 1;
$name = $_POST['name'];
$visitor_email = $_POST['email'];
function get_form_data(){
global $REQUEST_METHOD;
global $_POST;
global $_GET;
$vars = ($REQUEST_METHOD == 'GET') ? $_GET : $_POST;
//strip spaces from all fields
foreach ($vars as $k=>$v) $vars[$k] = trim($v);
return $vars;
}
function _build_fields($vars){
$skip_fields = array(
'name',
'email',
'subject',
'submitbtn');
// order by numeric begin, if it exists
$is_ordered = 0;
foreach ($vars as $k=>$v)
if (in_array($k, $skip_fields)) unset($vars[$k]);
$new_vars = array();
foreach ($vars as $k=>$v){
// remove _num, _reqnum, _req from end of field names
$k = preg_replace('/_(req|num|reqnum)$/', '', $k);
// check if the fields is ordered
//if (preg_match('/^\d+[ \:_-]/', $k)) $is_ordered++;
//remove number from begin of fields
$k = preg_replace('/^\d+[ \:_-]/', '', $k);
$new_vars[$k] = $v;
}
$vars = $new_vars;
$max_length = 10; // max length of key field
foreach ($vars as $k=>$v) {
$klen = strlen($k);
if (($klen > $max_length) && ($klen < 40))
$max_length = $klen;
}
if ($is_ordered)
ksort($vars);
// make output text
$out = "";
foreach ($vars as $k=>$v){
$k = str_replace('_', ' ', $k);
$k = ucfirst($k);
$len_diff = $max_length - strlen($k);
if ($len_diff > 0)
$fill = str_repeat('.', $len_diff);
else
$fill = '';
$out .= $k."$fill...: $v\n\n";
}
return $out;
}
$vars=get_form_data();
$out=_build_fields($vars);
$body = "A user $name submitted the form:\n\n".$out;
//Auto Responser Function To Send Auto Respond
$autoresponder_from = $your_email;
$subject = "Page Edit Request";
$autoresponder_subject = "%subject% (autoresponse)";
$autoresponder_message = <<<MSG
Hi %name%,
Thank you for submitting the form.
--
MSG;
function auto_respond($vars){
global $autoresponder_from, $autoresponder_message, $autoresponder_subject;
/// replace all vars in message
$msg = $autoresponder_message;
preg_match_all('/%(.+?)%/', $msg, $out);
$s_vars = $out[1]; //field list to substitute
foreach ($s_vars as $k)
$msg = str_replace("%$k%", $vars[$k], $msg);
/// replace all vars in subject
$subj = $autoresponder_subject;
preg_match_all('/%(.+?)%/', $subj, $out);
$s_vars = $out[1]; //field list to substitute
foreach ($s_vars as $k)
$subj = str_replace("%$k%", $vars[$k], $subj);
//
$_send_to = "$vars[name] <".$vars[email_from].">";
$_send_from = $autoresponder_from;
mail($_send_to, $subj, $msg, "From: $_send_from");
}
if(empty($errors))
{
//send the email
$to = $your_email;
$subject="Page Edit Request";
$from = $visitor_email;
$ip = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '';
//Attach File if Attachment is done
$files = array(); //files (field names) to attach in mail
if (count($_FILES) && $attachment_enabled)
{
$files = array_keys($_FILES);
}
/*print_r($files);
exit;*/
if (count($files)){
foreach ($files as $file){
echo "hello";
$file_name = $_FILES[$file]['name'];
$file_type = $_FILES[$file]['type'];
$file_tmp_name = $_FILES[$file]['tmp_name'];
$file_cnt = "";
if($file_name!='')
{
$f=#fopen($file_tmp_name, "rb");
if (!$f)
continue;
while($f && !feof($f))
$file_cnt .= fread($f, 4096);
fclose($f);
if (!strlen($file_type)) $file_type="applicaton/octet-stream";
if ($file_type == 'application/x-msdownload')
$file_type = "applicaton/octet-stream";
$date_time = date('Y-m-d H:i:s');
$mime_delimiter = md5(time());
$mail = <<<EOF
This is a MIME-encapsulated message
--$mime_delimiter
$body
--------------------
REMOTE IP : $REMOTE_ADDR
DATE/TIME : $date_time
EOF;
$data= chunk_split(base64_encode($file_cnt));
$mail .= "\n--$mime_delimiter\n";
$mail.="Content-Type: {\"application/octet-stream\"};\n" . " name=\"$file_name\"\n"."Content-Disposition: attachment;\n" . " filename=\"$file_name\"\n"."Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
// $mail .= "Content-type: $file_type\n";
// $mail .= "Content-Disposition: attachment; filename=\"$file_name\"\n";
// $mail .= "Content-Transfer-Encoding: base64\n\n";
// $mail .= chunk_split(base64_encode($file_cnt));
}
else
{
$mail=$body;
}
}
$mail .= "\n--$mime_delimiter--";
}
else
{
$mail=$body;
}
$headers = "Mime-Version: 1.0\r\nFrom: $from \r\nContent-Type: multipart/mixed;\n boundary=\"$mime_delimiter\"\r\nContent-Disposition: inline";
$headers .= "Reply-To: $visitor_email \r\n";
mail($to,'Page Edit Request', $mail,$headers);
if ($autoresponder_enabled)
auto_respond($vars);
header("Location: $redirect_url");
}
// Function to validate against any email injection attempts
function IsInjected($str)
{
$injections = array('(\n+)',
'(\r+)',
'(\t+)',
'(%0A+)',
'(%0D+)',
'(%08+)',
'(%09+)'
);
$inject = join('|', $injections);
$inject = "/$inject/i";
if(preg_match($inject,$str))
{
return true;
}
else
{
return false;
}
}
?>
Your mail composition is both extremely ugly and extremely wrong. The best suggestion I can give you is to stop reinventing the wheel and just use Swift mailer: http://swiftmailer.org/
I've used their tool a few times and it just works!
Edit not sure why this was downvoted, but fwiw this is the code for Swift:
$message = Swift_Message::newInstance()
->setSubject('Page Edit Request')
->setFrom(array($visitor_email))
->setTo(array($your_email))
->setBody($body);
if ($_FILES) {
foreach (array_keys($_FILES) as $file) {
if (UPLOAD_ERR_OK != $_FILES[$file]['error'] || !is_readable($_FILES[$file]['tmp_name'])) {
continue;
}
$message->attach(Swift_Attachment::fromPath($_FILES[$file]['tmp_name']));
}
}
$transport = Swift_MailTransport::newInstance();
$mailer = Swift_Mailer::newInstance($transport);
$numSent = $mailer->send($message);

Categories