i have use this code in php mail send with attachment. I am using the Apache http server with wamp.
<?php $to = 'santosh_091020#rediffmail.com';
// Declaring the necessary variables for mail sending :
$subject = 'Testing sendmail.exe';
$name = $_REQUEST['name'] ;
$email = $_REQUEST['email'] ;
$mob = $_REQUEST['mob'] ;
$msg = $_REQUEST['msg'] ;
$message = ' santosh enquire \n\nName: '.$name.' \n Email:'. $email.' \n Mobile:'. $mob.' \n Message: '.$msg.' \n ';
// Declaration of the attributes for attachment.
$upload_name=$_FILES["upload"]["name"];
$upload_type=$_FILES["upload"]["type"];
$upload_size=$_FILES["upload"]["size"];
$upload_temp=$_FILES["upload"]["tmp_name"];
$fp = fopen($upload_temp, "rb");
$file = fread($fp, $upload_size);
fclose($fp);
$file = chunk_split(base64_encode($file));
$num = md5(time());
// Defining the contents of the header.
$headers = "From: ".$email. "\r\n" . "CC: santosh#creativecrows.com" ;
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: multipart/mixed; ";
$headers .= "boundary=".$num."\r\n";
$headers .= "--$num\r\n";
//$headers .= "Message-ID: <".gettimeofday()." TheSystem#".$_SERVER['SERVER_NAME'].">\r\n";
$headers .= "X-Mailer: PHP v".phpversion()."\r\n";
$headers .= "Content-Type: text/html; charset=iso-8859-1\r\n";
$headers .= "Content-Transfer-Encoding: 8bit\r\n";
$headers .= "".$message."\n";
$headers .= "--".$num."\n";
$headers .= "Content-Type:".$upload_type." ";
$headers .= "name=\"".$upload_name."\"r\n";
$headers .= "Content-Transfer-Encoding: base64\r\n";
$headers .= "Content-Disposition: attachment; ";
$headers .= "filename=\"".$upload_name."\"\r\n\n";
$headers .= "".$file."\r\n";
$headers .= "--".$num."--";
//$data = chunk_split(base64_encode($data));
// sending the mail.
if(mail($to, $subject, $message, $headers))
{
echo "Email sent";
send();
}
else
{
echo "Email sending failed";
}
//send mail in client
function send()
{
$email = $_REQUEST['email'] ;
$name = $_REQUEST['name'] ;
$to= trim($email);
$subject = 'thanx';
$message = '<html><head><title>HTML email</title></head>
<body style="background-color:#000099;"><p style="color:#000099;">This email contains HTML Tags!</p><table><tr><th>Firstname</th><th>Lastname</th></tr><tr><td>John</td><td>Doe</td></tr></table></body></html>';$headers1 = 'MIME-Version: 1.0' . "\r\n";
$headers1.= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers1.= "From: ".$email;
if(mail($to, $subject, $message,$headers1))
{
echo "Email sent";
}
else
{
echo "Email sending failed";
echo $to;
echo $subject;
echo $message;
}
}
?>
but i got the following error;
Delivery to the following recipient failed permanently:
1.0#localhost
Technical details of permanent failure:
DNS Error: Domain name not found.
please help me. Thnx in advance.
Check this URL,
seems your header info is not absolute
http://webcheatsheet.com/php/send_email_text_html_attachment.php
$mail = new PHPMailer;
$mail->IsSMTP(); // Set mailer to use SMTP
$mail->Host = ''; // Specify main and backup server
$mail->Port = '';
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = ''; // SMTP username
$mail->Password = ''; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable encryption, 'ssl' also accepted
$mail->From = '';
$mail->FromName = '';
$mail->AddAddress($row['client_email'], ''); // Add a recipient
$mail->AddReplyTo('', 'Information');
$mail->AddCC('cc#example.com');
$mail->AddBCC('bcc#example.com');
$mail->WordWrap = 50;
// Set word wrap to 50 characters
$mail->AddAttachment('kurtacompany/techreporting/upload/"'.$row['file1'].'"'); // Add attachments
$mail->IsHTML(true); // Set email format to HTML
$mail->Subject = '';
$mail->Body = '<p>type whatever you want</p>';
if(!$mail->Send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
exit;
}
echo 'Message has been sent';
Related
I develop the custom Elementor widget. This is the form with two fields - email and name. Also, I have a form handler which must send the email from this form. In my widget, I added action="sender.php". In sender.php I write the code to send an email. But it does not send any emails. I also added SMTP features for PHPMailer in function.php. But t still does not work! Please, can you help me!!
sender.php
<?php
$phone = htmlspecialchars($_POST["phone"]);
$name = htmlspecialchars($_POST["name"]);
$toEmail = 'myemail#gmail.com';
$subject = 'New email';
$body ='
<h4>Name: </h4><p>'.$name.'</p>
<h4>Phone: </h4><p>'.$phone.'</p>';
$headers = "MIME-Version:1.0"."\r\n";
$headers .= "Content-Type:text/html;charset=UTF-8" . "\r\n";
$headers .="From: ".$name."<".$name.">". "\r\n";
if(mail($toEmail, $subject, $body,$headers)){
echo 'send';
};
?>
functionp.php
add_action( 'phpmailer_init', 'set_phpmailer_details' );
function set_phpmailer_details( $phpmailer) {
$phpmailer->isSMTP();
$phpmailer->Host = 'smtp.googlemail.com';
$phpmailer->SMTPAuth = true;
$phpmailer->Port = 465;
$phpmailer->Username = 'myemail#gmail.com';
$phpmailer->Password = '******';
$phpmailer->SMTPSecure = 'ssl';
}
Ok, It seems I solved the problem! In sender.php I added in the beginning
require('../../../../wp-load.php');
And after that my code to send the email:
$phone = htmlspecialchars($_POST["phone"]);
$name = htmlspecialchars($_POST["name"]);
$to ='myemail#gmail.com';
$subject = 'Subject';
$body ='
<b>Name: </b><span>'.$name.'</span><br>
<b>Phone: </b><span>'.phone.'</span>
$headers = "MIME-Version:1.0"."\r\n";
$headers .= "Content-Type:text/html;charset=UTF-8" . "\r\n";
$headers .="From: ".$name."<".$name.">". "\r\n";
wp_mail( $to, $subject, $body, $headers );
And installed the SMTP plugin for smtp.
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';
}
I would like to know about attaching multiple attachment in single mail and send . Please refer my following oode. In this only one file is getting attached. That is second file. First file is not at all considering for attaching. But file is being created properly in the path specified.
$filename=array($filenamee1 ,$filenamee2);
for($x=0;$x<count($filename);$x++){
echo $path.$filename[$x];
$file = $path.$filename[$x];
$file_size = filesize($file);
$handle = fopen($file, "r");
$content = fread($handle, $file_size);
fclose($handle);
$content = chunk_split(base64_encode($content));
$uid = md5(uniqid(time()));
$name = basename($file);
$header = "From: ".$from_name." <".$from_mail.">\r\n";
$header .= "cc: ".$mailtoCC."\r\n";
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-Type: multipart/mixed; boundary=\"".$uid."\"\r\n\r\n";
$header .= "This is a multi-part message in MIME format.\r\n";
$header .= "--".$uid."\r\n";
$header .= "Content-type:text/html; charset=iso-8859-1\r\n";
$header .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
$header .= $message."\r\n\r\n";
$header .= "--".$uid."\r\n";
$header .= "Content-Type: application/octet-stream; name=\"".$filename[$x]."\"\r\n";
$header .= "Content-Transfer-Encoding: base64\r\n";
$header .= "Content-Disposition: attachment; filename=\"".$filename[$x]."\"\r\n\r\n";
$header .= $content."\r\n\r\n";
$header .= "--".$uid."--";
}
if (mail($mailto, $subject, "", $header)) {
echo "<br>mail sent Successfully... OK";
} else {
echo "<br>mail send ... ERROR!";
}
Following the reusability principles, you can use https://github.com/PHPMailer/PHPMailer
<?php
require 'PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp1.example.com;smtp2.example.com'; // Specify main and backup server
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'jswan'; // SMTP username
$mail->Password = 'secret'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable encryption, 'ssl' also accepted
$mail->From = 'from#example.com';
$mail->FromName = 'Mailer';
$mail->addAddress('josh#example.net', 'Josh Adams'); // Add a recipient
$mail->addAttachment('/var/tmp/file.tar.gz'); // Add attachments
$mail->addAttachment('/tmp/image.jpg', 'new.jpg'); // Optional name
$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;
exit;
}
echo 'Message has been sent';
Source: How to attach two or multiple files and send mail in PHP
This is what I came up with for multiple files with form file name userfile:
for($ct=0;$ct<count($_FILES['userfile']['tmp_name']);$ct++)
{
$uploadfile = tempnam(sys_get_temp_dir(), sha1($_FILES['userfile']['name'][$ct]));
$filename =$_FILES['userfile']['name'][$ct];
if (move_uploaded_file($_FILES['userfile']['tmp_name'][$ct], $uploadfile)) {
$mail->addAttachment($uploadfile, $filename);
}
}
if ($mail->send()) {
echo "Sent";
} else {
echo "Mailer Error: " . $mail->ErrorInfo;
}
For those who want to send multiple files using phpMailer and input file multiple.
I joined and used the above two codes of #Rishi and #Matheno to achieve this result that dinamically add attachments selecteds by user.
On your input file name remember to put brackets:
<input type="file" multiple="multiple" name="attach_file[]" />
On your php send file:
Instead of:
$mail->addAttachment('/var/tmp/file.tar.gz');
Use:
for($ct=0;$ct<count($_FILES['attach_file']['tmp_name']);$ct++){
$mail->AddAttachment($_FILES['attach_file']['tmp_name'][$ct],$_FILES['attach_file']['name'][$ct]);
}
I've recently moved hosts and now with the contact form I have to use SMTP. I have been able with some help get something to work but am unable to retrieve the information I need from the form. The information I am trying to pull is name email phone and message. This is what I have been using
<?php
require "email.php";
$mail = new EMail;
$mail->Username = 'username.co.uk';
$mail->Password = 'mypassword';
$mail->SetFrom("no-reply#mywebsite.co.uk","no-reply#mywebsite.co.uk"); // Name is optional
$mail->AddTo("no-reply#mywebsite.co.uk","no-reply#mywebsite.co.uk"); // Name is optional
$mail->Subject = "Hello World Again!";
$mail->Message = "Hello World!";
//Optional
$mail->ContentType = "text/html"; // Defaults to "text/plain; charset=iso-8859-1"
$mail->Headers['X-SomeHeader'] = 'abcde'; // Set some extra headers if required
$mail->ConnectTimeout = 30; // Socket connect timeout (sec)
$mail->ResponseTimeout = 8; // CMD response timeout (sec)
$success = $mail->Send();
?>
When I test this an email gets sent but of course only the "Hello World" text gets sent as I'm unsure where to put the necessary code to pull the info I need.
Prior to moving hosts and not needing SMTP I was using this script
<?php
//-----------------------------------------------------
//-----------------------------------------------------
$address= "myemail.co.uk";
//-----------------------------------------------------
//-----------------------------------------------------
$name = $_REQUEST["name"];
$email = $_REQUEST["email"];
$phone = $_REQUEST["phone"];
$message_content = $_REQUEST["message"];
$mime_boundary = md5(time());
$headers = "From: $name <$email>\n";
$headers .= "Reply-To: $subject <$email>\n";
$headers .= "MIME-Version: 1.0\n";
$headers .= "Content-Type: multipart/alternative; boundary=\"$mime_boundary\"\n";
$message = "-- $mime_boundary\n\n";
$message .= "New email from the Commons website: \n\n\n";
$message .= "Name: $name \n\n";
$message .= "Email: $email \n\n";
$message .= "Phone: $phone \n\n";
$message .= "Message: $message_content \n\n";
$message .= "--$mime_boundary--\n\n";
$mail_sent = mail($address, $subject, $message, $headers);
echo $mail_sent ? "Success, mail sent!" : "Mail failed";
?>
Thanks in advance
Kind Regards
Tim
Did u try as this way???
$message_str = str_replace("[first_name]", $fname, $message_str);
$message_str = str_replace("[last_name]", $lname, $message_str);
$message_str = str_replace("[site_name]", "RMS", $message_str);
// 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: <norply#rms.com>' . "\r\n";
$subject = "activate account!";
if (mail("asd#sad.com", $subject, $message_str, $headers)) {
echo"Email successfully sent!";
} else {
echo"Email delivery failed…";
}
Just USe Php Mail function
consider below code
$subject = 'Welcome To demo.com';
$mydata['name'] = 'demo';
$mydata['user_name'] = 'test1';
$mydata['email'] = test#gmail.com;
$mydata['password'] = $password;
$mydata = (object)$mydata;
$message = "<div style='height: 500px; background: none repeat scroll 0% 0% rgb(241, 241, 241); border: 1px solid rgb(6, 106, 117); width: 450px;'>
<div style='width: 100%; background: none repeat scroll 0% 0% rgb(6, 106, 117); height: 80px;'>
<div style='width:150px; height:100px;margin:8px; float:left'>
</div>
</div>
<div style='width:100%;height:360px; margin: auto; float:left; text-align: center;'>
<h2>Hello $mydata->name </h2>
<h3>Here is you login details for Demo</h3>
<br>
<h3>Username: $mydata->user_name</h3>
<h3>Password: $mydata->password</h3>
</div>
<div style='height:30px;padding-top:10px;float:left; width:100%;text-align:center;background:#1d5770;'>
<span style='color:#fff;font-weight:bold'>demo Team</span>
</div>
</div>";
//$message = "<br><br>Username:$mydata->user_name <br><br><br>Password:$mydata->password <br>";
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= "To: $mydata->name <$mydata->email>" . "\r\n";
$headers .= "From: demo.com <contact#demo.com>" . "\r\n";
mail($mydata->email, $subject, $message, $headers);
for further reference follow these links
http://www.w3schools.com/php/php_ref_mail.asp
http://php.net/manual/en/function.mail.php
I used this however the message I get is that the email failed
<?php
require "email.php";
$mail = new EMail;
$mail->Username = 'myemail.co.uk';
$mail->Password = 'password';
$name = $_REQUEST["name"];
$email = $_REQUEST["email"];
$phone = $_REQUEST["phone"];
$message_content = $_REQUEST["message"];
$mime_boundary = md5(time());
$headers = "From: $name <$email>\n";
$headers .= "Reply-To: $subject <$email>\n";
$headers .= "MIME-Version: 1.0\n";
$headers .= "Content-Type: multipart/alternative; boundary=\"$mime_boundary\"\n";
$message = "-- $mime_boundary\n\n";
$message .= "New email from the Commons website: \n\n\n";
$message .= "Name: $name \n\n";
$message .= "Email: $email \n\n";
$message .= "Phone: $phone \n\n";
$message .= "Message: $message_content \n\n";
$message .= "--$mime_boundary--\n\n";
echo $mail_sent ? "Success, mail sent!" : "Mail failed";
?>
i've this script that works perfectly but the attachments are null (i mean i can see the attachments..but every file I load is 0 kb as size)
here is the code :
allegato means attachment
$path = $allegato['tmp_name'];
$fp = fopen($path, 'r');
do //we loop until there is no data left
{
$data = fread($fp, 8192);
if (strlen($data) == 0) break;
$content .= $data;
} while (true);
$content_encode = chunk_split(base64_encode($content));
$mime_boundary = "<<<--==+X[".md5(time())."]";
$headers .= "From:".$email."\r\n";
$headers .= "To: me <mail#gmail.com>\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: multipart/mixed;\r\n";
$headers .= " boundary=\"".$mime_boundary."\"";
$message .= "This is a multi-part message in MIME format.\r\n";
$message .= "\r\n";
$message .= "--".$mime_boundary."\r\n";
$message .= "Content-Type: text/plain; charset=\"iso-8859-1\"\r\n";
$message .= "Content-Transfer-Encoding: 7bit\r\n";
$message .= "\r\n";
$message .= "Email sent from:".$nome." \r\n";
$message .= $messaggio."\r\n";
$message .= "--".$mime_boundary."\r\n";
$message .= "Content-Type: ".$allegato_type."\"\r\n";
$message .= " name=\ ".$allegato_name."\"\r\n";
$message .= "Content-Transfer-Encoding: base64\r\n";
$message .= "Content-Disposition: attachment;\r\n";
$message .= " filename=\ ".$allegato_name."\"\r\n";
$message .= "\r\n";
$message .= $content_encode;
$message .= "\r\n";
$message .= "--".$mime_boundary."\r\n";
$ok = mail("mail#gmail.com", $object, $message, $headers);
if($ok)
{
echo'<script type="text/javascript">alert("mail sent successfully ! ");</script>';
}
else
{ echo'<script type="text/javascript">alert("mail failed! ");</script>';}
can someone help with attachments please ?(every file sent is 0 kb, how i fix it ?)
I suggest to use PHPMailer!
It is freely available from http://sourceforge.net/projects/phpmailer/
Just put it in a directory on the server, include its main php and your life will become a joy when sending e-mails from php.
I have a function for an easy start that I can provide to you for quick results:
require("/path/to/class.phpmailer.php");
function mail_sender($from_name,$from_email,$to_email,$subject,$mailtext,$att = false) {
$mail = new PHPMailer();
$mail->IsSMTP(); // set mailer to use SMTP
$mail->Host = "localhost"; // specify main and backup server
$mail->SMTPAuth = false; // turn on SMTP authentication
$mail->From = $from_email;
$mail->FromName = $from_name;
$mail->WordWrap = 50; // set word wrap to 50 characters
$mail->IsHTML(true); // set email format to HTML
$mail->CharSet="utf-8";
$mail->Subject = $subject;
$mail->Body = $mailtext;
$mail->AltBody = "";
$mail->AddAddress($to_email);
if ($att) {
$mail->AddAttachment("include/attachment.doc");
}
if(!$mail->Send()) {
echo "Message could not be sent. <p>";
echo "Mailer Error: " . $mail->ErrorInfo;
exit;
}
}