<?php
if
(isset(
$_POST
[
'button'
]) && isset(
$_FILES
[
'attachment'
]))
{
$from_email
=
'sender@abc.com'
;
$recipient_email
=
'recipient@xyz.com'
;
$sender_name
=
$_POST
[
"sender_name"
];
$reply_to_email
=
$_POST
[
"sender_email"
];
$subject
=
$_POST
[
"subject"
];
$message
=
$_POST
[
"message"
];
$tmp_name
=
$_FILES
[
'attachment'
][
'tmp_name'
];
$name
=
$_FILES
[
'attachment'
][
'name'
];
$size
=
$_FILES
[
'attachment'
][
'size'
];
$type
=
$_FILES
[
'attachment'
][
'type'
];
$error
=
$_FILES
[
'attachment'
][
'error'
];
if
(
$error
> 0)
{
die
(
'Upload error or No files uploaded'
);
}
$handle
=
fopen
(
$tmp_name
,
"r"
);
$content
=
fread
(
$handle
,
$size
);
fclose(
$handle
);
$encoded_content
=
chunk_split
(
base64_encode
(
$content
));
$boundary
= md5(
"random"
);
$headers
=
"MIME-Version: 1.0\r\n"
;
$headers
.=
"From:"
.
$from_email
.
"\r\n"
;
$headers
.=
"Reply-To: "
.
$reply_to_email
.
"\r\n"
;
$headers
.=
"Content-Type: multipart/mixed;"
;
$headers
.=
"boundary = $boundary\r\n"
;
$body
=
"--$boundary\r\n"
;
$body
.=
"Content-Type: text/plain; charset=ISO-8859-1\r\n"
;
$body
.=
"Content-Transfer-Encoding: base64\r\n\r\n"
;
$body
.=
chunk_split
(
base64_encode
(
$message
));
$body
.=
"--$boundary\r\n"
;
$body
.=
"Content-Type: $type; name="
.
$name
.
"\r\n"
;
$body
.=
"Content-Disposition: attachment; filename="
.
$name
.
"\r\n"
;
$body
.=
"Content-Transfer-Encoding: base64\r\n"
;
$body
.=
"X-Attachment-Id: "
.rand(1000, 99999).
"\r\n\r\n"
;
$body
.=
$encoded_content
;
$sentMailResult
= mail(
$recipient_email
,
$subject
,
$body
,
$headers
);
if
(
$sentMailResult
){
echo
"<h3>File Sent Successfully.<h3>"
;
}
else
{
die
("Sorry but the email could not be sent.
Please go back
and
try
again!");
}
}
?>
<!DOCTYPE html>
<html lang=
"en"
>
<head>
<meta charset=
"UTF-8"
>
<meta http-equiv=
"X-UA-Compatible"
content=
"IE=edge"
>
<meta name=
"viewport"
content=
"width=device-width, initial-scale=1.0"
>
<title>Send Attachment With Email</title>
</head>
<body>
<div style=
"display:flex; justify-content: center; margin-top:10%;"
>
<form enctype=
"multipart/form-data"
method=
"POST"
action=
""
style=
"width: 500px;"
>
<div
class
=
"form-group"
>
<input
class
=
"form-control"
type=
"text"
name=
"sender_name"
placeholder=
"Your Name"
required/>
</div>
<div
class
=
"form-group"
>
<input
class
=
"form-control"
type=
"email"
name=
"sender_email"
placeholder=
"Recipient's Email Address"
required/>
</div>
<div
class
=
"form-group"
>
<input
class
=
"form-control"
type=
"text"
name=
"subject"
placeholder=
"Subject"
/>
</div>
<div
class
=
"form-group"
>
<textarea
class
=
"form-control"
name=
"message"
placeholder=
"Message"
></textarea>
</div>
<div
class
=
"form-group"
>
<input
class
=
"form-control"
type=
"file"
name=
"attachment"
placeholder=
"Attachment"
required/>
</div>
<div
class
=
"form-group"
>
<input
class
=
"btn btn-primary"
type=
"submit"
name=
"button"
value=
"Submit"
/>
</div>
</form>
</div>
</body>
</html>