PHP email form WITH ATTACHMENT (with or without PHPmailer) - php

I am using the below PHP code that takes values from an HTML form and sends an email in HTML. This works fine for me.
Now I need to add an ATTACHMENT field that will send the attachment along with the email (with or without storing the file on the server). Can someone please suggest how to do it with or without PHPmailer?
Thanks!
<?php
if(empty($_POST['name']) || empty($_POST['email']) || empty($_POST['address'])) {
die('Error: Missing variables');
}
$name=$_POST['name'];
$mobile=$_POST['mobile'];
$position=$_POST['position'];
$email=$_POST['email'];
$message=$_POST['message'];
$ip=$_SERVER['REMOTE_ADDR'];
$to="email#server.com";
$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/plain; charset=utf-8\r\n";
$headers = 'From: '.$_POST['name'].' <'.$_POST['email'].'>';
'X-Mailer: PHP/' . phpversion();
$subject='Job Application from '.$name."\n\n\n";
$body.='Name: <b>'.$name."</b><br>\n";
$body.='Mobile No: <b>'.$mobile."</b><br>\n";
$body.='Position: <b>'.$position."</b><br>\n";
$body.='Email: <b>'.$email."</b><br>\n";
$body.='Message: <b>'.$message."</b><br>\n";
$body.='IP address of the submitter: '."\n".$ip."\n";
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= 'From: '.$email."\r\n";
if(mail($to, $subject, $body, $headers)) {
header("Location: thank-you.html");
} else {
echo "Something has gone wrong! Please try again!";
}
?>

It's easier to use PHPMailer..
You can get the documentation and tutorial here.
This is the code for a basic mail and attaching files:
<?php
require_once('../class.phpmailer.php');
$mail = new PHPMailer(); // defaults to using php "mail()"
$body = file_get_contents('contents.html');
$body = eregi_replace("[\]",'',$body);
$mail->AddReplyTo("name#yourdomain.com","First Last");
$mail->SetFrom('name#yourdomain.com', 'First Last');
$mail->AddReplyTo("name#yourdomain.com","First Last");
$address = "whoto#otherdomain.com";
$mail->AddAddress($address, "John Doe");
$mail->Subject = "PHPMailer Test Subject via mail(), basic";
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
$mail->MsgHTML($body);
$mail->AddAttachment("images/phpmailer.gif"); // attachment
$mail->AddAttachment("images/phpmailer_mini.gif"); // attachment
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent!";
}
Hope this helps.

$filePath = 'foldername/attachment.zip';
$file = fopen($filePath,'rb');
$data = fread($file,filesize($filePath));
fclose($file);
$data = chunk_split(base64_encode($data));
Content-Type: application/zip; name="attachment.zip"
Content-Transfer-Encoding: base64
Content-Disposition: attachment
$data
Add this code before this line "if(mail($to, $subject, $body, $headers)) {".

Related

sending mail from php when link in message body

i have a php script
<?php
$to = 'somebody#somedomain.com';
$subject = 'Test mail';
$message = 'mysitedomain.com';
$from = 'support#mysitedomain.com';
$headers = 'From:' . $from;
mail($to,$subject,$message,$headers);
echo 'Mail Sent.';
?>
When i run this code mail not send. If i change message to mysitedomaincom (without dot before com) the mail send succesfull.
Anybody have a solution for this?
This codes that tells the mailer and the recipient that the email contains well formed HTML that it will need to interpret
If you want you can change content of $message, now with this codes you can send HTML content mail.
<?PHP
$to = 'somebody#somedomain.com';
$subject = 'Test mail';
$headers = "From: Support <support#mysitedomain.com>" . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$message = '<html><body>';
$message .= '<h1>mysitedomain.com</h1>';
$message .= '</body></html>';
mail($to, $subject, $message, $headers);
?>

php mail() function, headers issue, can not send an email

I know this is really common issue, but I have problem with headers. This function send email only when I send mail with $header2. In other cases I get fail echo. Does not working with $headers.
I don't know why it is happening, also it doesn't work with php.net default headers below:
$headers = 'From: webmaster#example.com' . "\r\n" .
'Reply-To: webmaster#example.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
Complete function:
function sendMail() {
$to = "mymail#gmail.com";
$subject = "This is subject";
$message = "<b>This is HTML message.</b>";
$message .= "<h1>This is headline.</h1>";
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
// Additional headers
$headers .= 'To: Mary <mary#example.com>, Kelly <kelly#example.com>' . "\r\n";
$headers .= 'From: Birthday Reminder <birthday#example.com>' . "\r\n";
$headers .= 'Cc: birthdayarchive#example.com' . "\r\n";
$headers .= 'Bcc: birthdaycheck#example.com' . "\r\n";
$header2 = "From:abc#somedomain.com \r\n";
$header2 = "Cc:afgh#somedomain.com \r\n";
$header2 .= "MIME-Version: 1.0\r\n";
$header2 .= "Content-type: text/html\r\n";
$retval = mail ($to, $subject, $message, $headers);
if( $retval == true ) {
echo "Message sent successfully...";
}else {
echo "Message could not be sent...";
}
}
Firstly, just get rid of this entire code block since there is no reference to your usage of the $headers2 variable. Do go over my answer in its entirety.
$header2 = "From:abc#somedomain.com \r\n";
$header2 = "Cc:afgh#somedomain.com \r\n";
// ^ BROKEN concatenate
$header2 .= "MIME-Version: 1.0\r\n";
$header2 .= "Content-type: text/html\r\n";
PHP is going over your entire code, regardless. And it contains a broken concatenate.
However, it's unclear as to what you want to do here and have obviously taken examples from the manual on mail() http://php.net/manual/en/function.mail.php then just blindly adding stuff in there.
Sidenote: The To: is already pre-determined as to where it should be sent to, so the use of To: in the headers isn't required.
function sendMail() {
$to = "mymail#gmail.com";
$subject = "This is subject";
$message = "<b>This is HTML message.</b>";
$message .= "<h1>This is headline.</h1>";
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
// Additional headers
$headers .= "From:abc#somedomain.com \r\n";
$headers .= "Cc:afgh#somedomain.com \r\n";
$retval = mail ($to, $subject, $message, $headers);
if( $retval == true ) {
echo "Message sent successfully...";
}else {
echo "Message could not be sent...";
}
}
and if the goal here is to send 2 seperate mails, then you will need to use 2 seperate mail() functions and 2 different header variables.
Something to which you can consult, as per an answer I once gave for another question:
https://stackoverflow.com/a/18382062/1415724
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// Then the rest of your code
Sidenote: Displaying errors should only be done in staging, and never production.
Please stop using the php mail() function! My advice will be to use PHPMailer and sending the emails via SMTP.
Here is a small code snippet using PHPmailer:
<?php
require 'PHPMailerAutoload.php';
$mail = new PHPMailer;
//$mail->SMTPDebug = 3; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtpserver.com'; // Specify main SMTP server. If you dont have one us GMAL or mandrill
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'user#youremail.com'; // SMTP username
$mail->Password = 'pass'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587; // TCP port to connect to
$mail->setFrom('from#youremail.com', 'Mailer');
$mail->addAddress('joe#youremail.net', 'Joe User'); // Add a recipient
$mail->addAddress('ellen#youremail.com'); // Name is optional
$mail->addReplyTo('info#youremail.com', 'Information');
$mail->addCC('cc#youremail.com');
$mail->addBCC('bcc#youremail.com');
$mail->addAttachment('/var/tmp/file.tar.gz'); // Add attachments
$mail->addAttachment('/tmp/image.jpg', 'new.jpg'); // Optional name
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'Here is the subject';
$mail->Body = 'This is the HTML message body <b>in bold!</b>';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent';
}

How to send a simple email using PHP code

I would like to send an email to my gmail account using some simple PHP code. The code below works in terms of execution, however the problem is even thought is says "Message Sent" I am not receiving my email in my gmail account. Please advice
ini_set('SMTP',"smtp.gmail.com");
$to ="example#gmail.com"; // this will be replaced with my actual email
$from ="example#gmail.com"; // this will be replaced with senders email
$message = $_GET['Message'];
$subject = "This is a test";
if(mail($to,$subject,$message,$from))
{
echo "Message Sent";
}
else
{
echo "Message Not Sent";
}
Steps to send a simple email
Go to google
Search for "PHP Mail"
Click the first result
Read, read, keep reading, wait, read it over, read on
Enjoy!
But seriously:
(Examples are taken from PHP.net)
Example 1
Sending a simple email
Using mail() to send a simple email:
<?php
// The message
$message = "Line 1\r\nLine 2\r\nLine 3";
// In case any of our lines are larger than 70 characters, we should use wordwrap()
$message = wordwrap($message, 70, "\r\n");
// Send
mail('caffeinated#example.com', 'My Subject', $message);
?>
Example 2
Sending mail with extra headers.
The addition of basic headers, telling the MUA the From and Reply-To addresses:
<?php
$to = 'nobody#example.com';
$subject = 'the subject';
$message = 'hello';
$headers = 'From: webmaster#example.com' . "\r\n" .
'Reply-To: webmaster#example.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $message, $headers);
?>
Use his line of code:
$to ="example#gmail.com"; // this will be replaced with my actual email
$from ="example#gmail.com"; // this will be replaced with senders email
$headers = "From: ".$from."\r\n";
$headers .= "Reply-To: ".$from."\r\n";
//$headers .= "CC: susan#example.com\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$message = $_GET['Message'];
$subject = "This is a test";
mail($to, $subject, $message, $headers);

PhP mail function returning true but mail is not delivered

I have a domain www.ipsmeerut.com, i m using the script below to send mail. It is returning true but mail is not sending.
Here's my script:
<?php
$to = 'brajnacs#gmail.com';
$subject = 'Test';
$headers = "From: Test<no-reply#ipsmeerut.com>\n";
$headers .= "MIME-Version: 1.0\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\n";
$message = "<html><body>";
$message .= "<h1>Hello, World!</h1>";
$message .= "</body></html>";
$res=false;
$res=mail($to, $subject, $message, $headers);
var_dump($res);
echo "Mail sent to ".$to;
?>
This script is working fine on my other domains. var_dump is showing true. My mail server is aspmx.l.google.com and I have also added MX Entry for it.
Use phpmailer, Try this
require_once('../class.phpmailer.php');
$mail = new PHPMailer(); // defaults to using php "mail()"
$body = 'you content goes here';
$body = eregi_replace("[\]",'',$body);
$mail->AddReplyTo("name#yourdomain.com","First Last");
$mail->SetFrom('name#yourdomain.com', 'First Last');
$mail->AddReplyTo("name#yourdomain.com","First Last");
$address = "whoto#otherdomain.com";
$mail->AddAddress($address, "John Doe");
$mail->Subject = "PHPMailer Test Subject via mail(), basic";
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
$mail->MsgHTML($body);
$mail->AddAttachment("images/phpmailer.gif"); // attachment
$mail->AddAttachment("images/phpmailer_mini.gif"); // attachment
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent!";
}
why not just using your default MX and try testing again? dose Google allows to send anonymous email with authentication?

Encoding PHP to send mails in other languege

I want to encode my php sending form in my language.
What is wrong with the code? I have added the content-type in the $headers at the end... It is not the whole file, there is also HTML after the PHP, but did not let me to post it
<?php
if(isset($_POST['email'])) {
// EDIT THE 2 LINES BELOW AS REQUIRED
$email_to = "gancho_lambev#abv.bg";
$email_subject = "Contact Form...";
function died($error) {
// your error code can go here
echo "We are very sorry, but there were error(s) found with the form your submitted. ";
echo "These errors appear below.<br /><br />";
echo $error."<br /><br />";
echo "Please go back and fix these errors.<br /><br />";
die();
}
// validation expected data exists
if(!isset($_POST['name']) ||
!isset($_POST['email']) ||
!isset($_POST['comments'])) {
died('We are sorry, but there appears to be a problem with the form your submitted.');
}
$name = $_POST['name']; // required
$email_from = $_POST['email']; // required
$comments = $_POST['comments']; // required
function clean_string($string) {
$bad = array("content-type","bcc:","to:","cc:","href");
return str_replace($bad,"",$string);
}
$email_message .= "Name: ".clean_string($name)."\n";
$email_message .= "Email: ".clean_string($email_from)."\n";
$email_message .= "Comments: ".clean_string($comments)."\n";
// create email headers
$headers .= 'Content-type: text/plain; charset=windows-1251' . "\r\n";
$headers = 'From: '.$email_from."\r\n".
'Reply-To: '.$email_from."\r\n" .
'X-Mailer: PHP/' . phpversion();
#mail($email_to, $email_subject, $email_message, $headers); ;}
?>
For sending mails in different language, you can just change the charset:
$headers .= 'Content-type: text/plain; charset=UTF-8' . "\r\n";
$headers .= 'From: '.$email_from."\r\n".
'Reply-To: '.$email_from."\r\n" .
'X-Mailer: PHP/' . phpversion();
And be sure the page is encoded as UTF-8 and that if a database is used, the table ( or whole db ) is in "UTF-8 unicode general"
With UTF-8 you can write the characters as they appear, don't use entities.
Do you mean something like this. Hope it helps
Try using a 3rd party library, like phpmailer:
Example: http://phpmailer.worxware.com/index.php?pg=exampleamail
Download: http://sourceforge.net/projects/phpmailer/files/phpmailer%20for%20php5_6/PHPMailer%20v5.1/
Don't forget to set the charset, like this:
<?php
require_once '../class.phpmailer.php';
$mail = new PHPMailer(true); //defaults to using php "mail()"; the true param means it will throw exceptions on errors, which we need to catch
$mail->CharSet = 'utf-8';
try {
$mail->AddReplyTo('name#yourdomain.com', 'First Last');
$mail->AddAddress('whoto#otherdomain.com', 'John Doe');
$mail->SetFrom('name#yourdomain.com', 'First Last');
$mail->AddReplyTo('name#yourdomain.com', 'First Last');
$mail->Subject = 'PHPMailer Test Subject via mail(), advanced';
$mail->AltBody = 'To view the message, please use an HTML compatible email viewer!'; // optional - MsgHTML will create an alternate automatically
$mail->MsgHTML(file_get_contents('contents.html'));
$mail->AddAttachment('images/phpmailer.gif'); // attachment
$mail->AddAttachment('images/phpmailer_mini.gif'); // attachment
$mail->Send();
echo "Message Sent OK\n";
} catch (phpmailerException $e) {
echo $e->errorMessage(); //Pretty error messages from PHPMailer
} catch (Exception $e) {
echo $e->getMessage(); //Boring error messages from anything else!
}
?>
Try the following:
Set the collation of your database/ tables/ rows to UTF-8. UTF8_general_ci should do.
Set the connection between MySQL and PHP to UTF-8. (By executing the query SET NAMES 'utf8' after connecting or by setting the default connection encoding).
Try sending the content-type header with PHP: header("Content-Type: text/html; charset=utf-8");.

Categories