I want to attach a image as an attachment using mail() function.
I am using xampp and want the image to be sent from my computer to an email id.
This code is sending text email easily:
<?php
if(mail('abc#gmail.com','Hello','Testing Testing','From:xyz#gmail.com'))
{
echo "Success";
} else {
echo "Fail";
}
?>
I want to add an image after it using normal mail method of php.
you need to use the pear library for composing or sending the mail.
include_once('Mail.php');
include_once('Mail_Mime/mime.php');
$message = new Mail_mime();
$message->setTXTBody($text);
$message->addAttachment($path_of_uploaded_file);
$body = $message->get();
$extraheaders = array("From"=>$from, "Subject"=>$subject,"Reply-To"=>$visitor_email);
$headers = $message->headers($extraheaders);
$mail = Mail::factory("mail");
$mail->send($to, $headers, $body);
here is a way
You could use the Mail class from the Zend library, very simple and no reliance on PEAR.
Its been covered in a previous question here.
I suggest to use Swiftmailer. It is up to date, easy to install and use. You can install it via PEAR, but there are lots of other options you might find more convenient as well.
Example code to send a mail with an attachement taken from the manual:
require_once 'lib/swift_required.php';
// Create the message
$message = Swift_Message::newInstance()
// Give the message a subject
->setSubject('Your subject')
// Set the From address with an associative array
->setFrom(array('john#doe.com' => 'John Doe'))
// Set the To addresses with an associative array
->setTo(array('receiver#domain.org', 'other#domain.org' => 'A name'))
// Give it a body
->setBody('Here is the message itself')
// And optionally an alternative body
->addPart('<q>Here is the message itself</q>', 'text/html')
// Optionally add any attachments
->attach(Swift_Attachment::fromPath('my-document.pdf'));
this is using php and ajax it will work 100%
<?php
include "db.php";
if(isset($_POST['tourid']))
{
$to=$_POST['email'];
$file_name = "test/sample.pdf";
require 'class/class.phpmailer.php';
$mail = new PHPMailer;
$mail->IsSMTP(); //Sets Mailer to send message using SMTP
$mail->Host = ''; //Sets the SMTP hosts of your Email hosting, this for Godaddy
$mail->Port = ''; //Sets the default SMTP server port
$mail->SMTPAuth = true; //Sets SMTP authentication. Utilizes the Username and Password variables
$mail->Username = ''; //Sets SMTP username
$mail->Password = ''; //Sets SMTP password
$mail->SMTPSecure = ''; //Sets connection prefix. Options are "", "ssl" or "tls"
$mail->From = ''; //Sets the From email address for the message
$mail->FromName = ''; //Sets the From name of the message
$mail->AddAddress($to, 'Name'); //Adds a "To" address
$mail->WordWrap = 50; `` //Sets word wrapping on the body of the message to a given number of characters
$mail->IsHTML(true); //Sets message type to HTML
$mail->AddAttachment($file_name); //Adds an attachment from a path on the filesystem
$mail->Subject = 'Customer Details'; //Sets the Subject of the message
$mail->Body = 'Please Find Tour details in attached PDF File.'; //An HTML or plain text message body
if($mail->Send()) //Send an Email. Return true on success or false on error
{
$message = '<label class="text-success">Tour Details has been send successfully...</label>';
echo $message;
unlink($file_name);
}
}
else
{
echo "sending error";
}
?>
Related
I have a problem sending multiple email addresses functions. If I send a single email address, I can work. If I send multiple emails to the receiver, they cannot receive my message. I am using the PHPMailer function to do the email function with XAMPP. I am using the PHP array function to put the receiver's address in the array and use the while function to loop the receiver address to send it.
Below is my coding:
$address = array('st9overfindsolution#gmail','st7overfindsolution#gmail');
require 'class/class.phpmailer.php';
$mail = new PHPMailer(true);
$mail->IsSMTP();
$mail->Host = 'smtp.gmail.com';
// $mail->SMTPDebug = 1;
$mail->Port = 465;
$mail->SMTPAuth = true;
$mail->Username = 'example#gmail.com';
$mail->Password = '1233aqqq';
$mail->SMTPSecure = 'ssl';
$mail->From = $_POST["email"];
$mail->FromName = $_POST["name"];
$mail->AddCC($_POST["email"], $_POST["name"]);
$mail->WordWrap = 50;
$mail->IsHTML(true);
$mail->Subject = $_POST["subject"];
$mail->Body = $_POST["message"];
while(list ($key, $val) = each($address)){
$mail->AddAddress($val);
}
What I've tried?
1.I put all receiver email addresses in the array $address = array('st9overfindsolution#gmail','st7overfindsolution#gmail'); and use below while function code, but cannot work.
2.If send single email address without using while function, just can work, like below coding:
Hope someone can guide me on how to solve this problem. Thanks.
i have created new function named "sendmyemail" and inserted the code inside this function, so you can sent multiple emails by calling this function with email address.
<?php
/**
* This example shows sending a message using a local sendmail binary.
*/
//Import the PHPMailer class into the global namespace
use PHPMailer\PHPMailer\PHPMailer;
require '../vendor/autoload.php';
function sendmyemail($whotoEmail){
//Create a new PHPMailer instance
$mail = new PHPMailer();
//Set PHPMailer to use the sendmail transport
$mail->isSendmail();
//Set who the message is to be sent from
$mail->setFrom('from#example.com', 'First Last');
//Set who the message is to be sent to
$mail->addAddress($whotoEmail);
//Set the subject line
$mail->Subject = 'PHPMailer sendmail test';
//Read an HTML message body from an external file, convert referenced images to
embedded,
//convert HTML into a basic plain-text alternative body
$mail->msgHTML(file_get_contents('contents.html'), __DIR__);
//Replace the plain text body with one created manually
$mail->AltBody = 'This is a plain-text message body';
//Attach an image file
$mail->addAttachment('images/phpmailer_mini.png');
//send the message, check for errors
if (!$mail->send()) {
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'Message sent to '.$whotoEmail.'!';
}
}
sendmyemail('abcduser#gmail.com');
sendmyemail('efguser#gmail.com');
sendmyemail('hijkuser#gmail.com');
sendmyemail('lmnouser#gmail.com');
I have a simple contact form below---
<html>
<head>
<title>Sending HTML email using PHP</title>
</head>
<body>
<?php
$to = "contact#mydomain.com";
$subject = "This is subject";
$message = "<b>This is HTML message.</b>";
$message .= "<h1>This is headline.</h1>";
$header = "From:jayaryaa#gmail.com \r\n";
//$header .= "Cc:no-reply#skynetinfosolution.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...";
}
?>
</body>
</html>
This script is working fine when I put my website email on place of $to , and when I enter my gmail id on place of FROM , my question is how can I send email to my gmail from my website email using mail function ? ,I have tried by putting my gmail id in place of $to and my website email in place of From but it's not working , My website is a shared linux hosting .
Take a look at the PHPMailer Github. When you use the PHP mail function, you are sending email directly from your web server.Sending mail via SMTP is recommended as email is sent from the mail server rather than local server. This script lets you send messages via your Google’s Gmail server. Example below
<?php
/**
* This example shows settings to use when sending via Google's Gmail servers.
* This uses traditional id & password authentication - look at the gmail_xoauth.phps
* example to see how to use XOAUTH2.
* The IMAP section shows how to save this message to the 'Sent Mail' folder using IMAP commands.
*/
//Import PHPMailer classes into the global namespace
use PHPMailer\PHPMailer\PHPMailer;
require '../vendor/autoload.php';
//Create a new PHPMailer instance
$mail = new PHPMailer;
//Tell PHPMailer to use SMTP
$mail->isSMTP();
//Enable SMTP debugging
// 0 = off (for production use)
// 1 = client messages
// 2 = client and server messages
$mail->SMTPDebug = 2;
//Set the hostname of the mail server
$mail->Host = 'smtp.gmail.com';
// use
// $mail->Host = gethostbyname('smtp.gmail.com');
// if your network does not support SMTP over IPv6
//Set the SMTP port number - 587 for authenticated TLS, a.k.a. RFC4409 SMTP submission
$mail->Port = 587;
//Set the encryption system to use - ssl (deprecated) or tls
$mail->SMTPSecure = 'tls';
//Whether to use SMTP authentication
$mail->SMTPAuth = true;
//Username to use for SMTP authentication - use full email address for gmail
$mail->Username = "username#gmail.com";
//Password to use for SMTP authentication
$mail->Password = "yourpassword";
//Set who the message is to be sent from
$mail->setFrom('from#example.com', 'First Last');
//Set an alternative reply-to address
$mail->addReplyTo('replyto#example.com', 'First Last');
//Set who the message is to be sent to
$mail->addAddress('whoto#example.com', 'John Doe');
//Set the subject line
$mail->Subject = 'PHPMailer GMail SMTP test';
//Read an HTML message body from an external file, convert referenced images to embedded,
//convert HTML into a basic plain-text alternative body
$mail->msgHTML(file_get_contents('contents.html'), __DIR__);
//Replace the plain text body with one created manually
$mail->AltBody = 'This is a plain-text message body';
//Attach an image file
$mail->addAttachment('images/phpmailer_mini.png');
//send the message, check for errors
if (!$mail->send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent!";
//Section 2: IMAP
//Uncomment these to save your message in the 'Sent Mail' folder.
#if (save_mail($mail)) {
# echo "Message saved!";
#}
}
//Section 2: IMAP
//IMAP commands requires the PHP IMAP Extension, found at: https://php.net/manual/en/imap.setup.php
//Function to call which uses the PHP imap_*() functions to save messages: https://php.net/manual/en/book.imap.php
//You can use imap_getmailboxes($imapStream, '/imap/ssl') to get a list of available folders or labels, this can
//be useful if you are trying to get this working on a non-Gmail IMAP server.
function save_mail($mail)
{
//You can change 'Sent Mail' to any other folder or tag
$path = "{imap.gmail.com:993/imap/ssl}[Gmail]/Sent Mail";
//Tell your server to open an IMAP connection using the same username and password as you used for SMTP
$imapStream = imap_open($path, $mail->Username, $mail->Password);
$result = imap_append($imapStream, $path, $mail->getSentMIMEMessage());
imap_close($imapStream);
return $result;
}
Isn't because your host prevent emails sending from another domain for spam issues ?
Eventually you can add a transfert rule from your Skynet to Gmail adress.
This question already has answers here:
Reintroduce $HTTP_POST_VARS in PHP 5.3
(4 answers)
Closed 8 years ago.
this is my code am not receiving any mail through this code.
$email = $HTTP_POST_VARS[email];
$mailto ="nr.shubha#gmail.com";
$mailsubj = "Form submission";
$mailhead = "From: $email\n";
reset ($HTTP_POST_VARS);
$mailbody = "Email form the web site form:\n";
echo $HTTP_POST_VARS;
while (list ($key, $val) = each ($HTTP_POST_VARS)) {
$mailbody .= "$key : $val\n";
}
if (!eregi("\n",$HTTP_POST_VARS[email])) {
mail($mailto, $mailsubj, $mailbody, $mailhead);
}
print_r($HTTP_POST_VARS);
I strongly suggest you to use premade classes like https://github.com/PHPMailer/PHPMailer
It's much "spam safe" than using plain PHP code, and helps you with image embedding, attachments, etc...
I recommend you to use PHPMailer Library. Works great.
Here is a sample of my work
require_once('phpmailer/class.phpmailer.php');
$mail = new PHPMailer();
$mail->IsSMTP(); // set mailer to use SMTP
//This part is for authentication
$mail->Host = "mail.example.com"; // specify main and backup server
$mail->SMTPAuth = "SMTPAuth"; // turn on SMTP authentication
$mail->Username = "user#example.com"; // SMTP username
$mail->Password = "****"; // SMTP password
//the receiver will see that the sender address is this
$mail->From = "ihavesentit#example.com";
$mail->FromName = "The Sender";
//You can use AddAdress() and AddCC() functions several times for different receivers
$mail->AddAddress("receiver#example.com");
$mail->AddCC('another_receiver#example.com');
$mail->AddReplyTo("reply-to-me#example.com");
$mail->WordWrap = 50; // set word wrap to 50 characters (arbitrary)
$mail->IsHTML(true); // set email format to HTML
$mail->Subject = "mail subject";
$mail->Body = "<p>mail content will be typed here</p>";
$mail->AltBody = "will be used if the receiver does not accept HTML content e-mails";
//final and the most important action
$mail->Send();
This is Work only on the live server when it will host. It will not work on the localhost.
Because the SMTP only work on the live hosted server not on the "localhost".
can anyone provide me the way of sending mail through php with attached object as well .plz i am new in this kindly help me in this. is there any server to be installed for this? the mail should this on any email account aswell plz help me in this.can any one provide me the link of tutorial i used the tutorial HERE it display me the error Fatal error: Call to undefined function IsSMTP() in C:\wamp\www\EMS3\mail.php on line 13 plz help me in this
There is an error in the example provided there. Use the following code.
require("phpmailer/class.phpmailer.php");
$mail = new PHPMailer();
$mail->IsSMTP(); // send via SMTP
$mail->SMTPAuth = true; // turn on SMTP authentication
$mail->Username = "username#gmail.com"; // SMTP username
$mail->Password = "password"; // SMTP password
$webmaster_email = "username#doamin.com"; //Reply to this email ID
$email="username#domain.com"; // Recipients email ID
$name="name"; // Recipient's name
$mail->From = $webmaster_email;
$mail->FromName = "Webmaster";
$mail->AddAddress($email,$name);
$mail->AddReplyTo($webmaster_email,"Webmaster");
$mail->WordWrap = 50; // set word wrap
$mail->AddAttachment("/var/tmp/file.tar.gz"); // attachment
$mail->AddAttachment("/tmp/image.jpg", "new.jpg"); // attachment
$mail->IsHTML(true); // send as HTML
$mail->Subject = "This is the subject";
$mail->Body = "Hi,
This is the HTML BODY "; //HTML Body
$mail->AltBody = "This is the body when user views in plain text format"; //Text Body
if(!$mail->Send())
{
echo "Mailer Error: " . $mail->ErrorInfo;
}
else
{
echo "Message has been sent";
}
?>
update you also need to set the external SMTP server your using. if your using google. i believe its smtp.gmail.com
$mail->Host = "smtp.gmail.com";
$mail->Port = 465;
$mail->Secure = "ssl";
You can use an external PHP library for sending mail, which I have used internally on a localhost, but still configured the parameters to send to external sources. The package is Swift Mailer.
In localhost you can't send any mail. After hosting only this is possible.
I am rather puzzled with this one.
//SMTP servers details
$mail->IsSMTP();
$mail->Host = "mail.hostserver.com";
$mail->SMTPAuth = false;
$mail->Username = $myEmail; // SMTP usr
$mail->Password = "****"; // SMTP pass
$mail->SMTPKeepAlive = true;
$mail->From = $patrickEmail;
$mail->FromName = "***";
$mail->AddAddress($email, $firstName . " " . $lastName);
$mail->WordWrap = 50;
$mail->IsHTML(true);
$mail->Subject = $client_subject;
$mail->Body = $client_msg;
if($mail->Send())
{
$mail->ClearAllRecipients();
$mail->ClearReplyTos();
$mail->ClearCustomHeaders();
...
$mail->From = "DO_NOT_REPLY#...";
$mail->FromName = "****";
$mail->AddAddress($ToEmail1, "***"); //To: (recipients).
$mail->AddAddress($ToEmail2, "***"); //To: (recipients).
$mail->WordWrap = 50;
$mail->IsHTML(true);
$mail->Subject = $notification_subject;
$mail->Body = $notification_msg;
if($mail->Send())
{
...
The first email sends fine. The second one doesn't. What could be the reason for that behavior? Am I missing some kind of reset?
Update: using a different mail server seems to work so apparently it's a setting of that specific mail server causing problems. Any idea what that could be?
Some providers impose restrictions on the number of messages that can be sent within a specific time span. To determine if your problem depends by a provider "rate limit", you should try to add a pause after the first send. For example:
if ($mail->Send()) {
sleep(10); // Seconds
...
if ($mail->Send()) {
...
}
}
Then, by progressively lowering the sleep time, you should be able to determine which is the rate limit.
Try this:
As #Felipe Alameda A mentioned Remove $mail->SMTPKeepAlive = true;
// for every mail
if(!$mail->Send())
{
echo 'There was a problem sending this mail!';
}
else
{
echo 'Mail sent!';
}
$mail->SmtpClose();
IMHO you need to create new PHPMailer object for every sent email. If you want to share some common setup, use something like this:
$mail = new PHPMailer();
/* Configure common settings */
while ($row = mysql_fetch_array ($result)) {
$mail2 = clone $mail;
$mail2->MsgHTML("Dear ".$row["fname"].",<br>".$cbody);
$mail2->AddAddress($row["email"], $row["fname"]);
$mail2->send();
}
I think your problem is $mail->SMTPAuth = false;
It is hard to believe there are ISP or SMTP providers that don't require authentication, even if they are free.
You may try this to check for errors instead of or in addition to checking for send() true:
if ( $mail->IsError() ) { //
echo ERROR;
}
else {
echo NO ERRORS;
}
//Try adding this too, for debugging:
$mail->SMTPDebug = 2; // enables SMTP debug information
Everything else in your code looks fine. We use PHPMailer a lot and never had any problems with it
The key may lie in the parts you have omitted. Is the domain of the sender of both emails the same? Otherwise the SMTP host may see this as a relay attempt. If you have access to the SMTP server logs, check these; they might offer a clue.
Also, check what $mail->ErrorInfo says... it might tell you what the problem is.
i personally would try to make small steps like sending same email.. so just clear recipients and try to send identical email (this code works for me). If this code passes you can continue to adding back your previous lines and debug where it fails
and maybe $mail->ClearCustomHeaders(); doing problems
//SMTP servers details
$mail->IsSMTP();
$mail->Host = "mail.hostserver.com";
$mail->SMTPAuth = false;
$mail->Username = $myEmail; // SMTP usr
$mail->Password = "****"; // SMTP pass
$mail->SMTPKeepAlive = true;
$mail->From = $patrickEmail;
$mail->FromName = "***";
$mail->AddAddress($email, $firstName . " " . $lastName);
$mail->WordWrap = 50;
$mail->IsHTML(true);
$mail->Subject = $client_subject;
$mail->Body = $client_msg;
// all above is copied
if($mail->Send()) {
sleep(5);
$mail->ClearAllRecipients();
$mail->AddAddress('another#email.com'); //some another email
}
...
Try with the following example.,
<?php
//error_reporting(E_ALL);
error_reporting(E_STRICT);
date_default_timezone_set('America/Toronto');
require_once('../class.phpmailer.php');
//include("class.smtp.php"); // optional, gets called from within class.phpmailer.php if not already loaded
$mail = new PHPMailer();
$body = file_get_contents('contents.html');
$body = eregi_replace("[\]",'',$body);
$mail->IsSMTP(); // telling the class to use SMTP
$mail->Host = "mail.yourdomain.com"; // SMTP server
$mail->SMTPDebug = 2; // enables SMTP debug information (for testing)
// 1 = errors and messages
// 2 = messages only
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->Host = "mail.yourdomain.com"; // sets the SMTP server
$mail->Port = 26; // set the SMTP port for the GMAIL server
$mail->Username = "yourname#yourdomain"; // SMTP account username
$mail->Password = "yourpassword"; // SMTP account password
$mail->SetFrom('name#yourdomain.com', 'First Last');
$mail->AddReplyTo("name#yourdomain.com","First Last");
$mail->Subject = "PHPMailer Test Subject via smtp, basic with authentication";
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
$mail->MsgHTML($body);
$address1 = "whoto#otherdomain.com";
$address2 = "whoto#otherdomain.com";
$mail->AddAddress($address1, "John Doe");
$mail->AddAddress($address2, "John Peter");
$mail->AddAttachment("images/phpmailer.gif"); // attachment if any
$mail->AddAttachment("images/phpmailer_mini.gif"); // attachment if any
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent!";
}
?>
Note : Better you can make a multiple user email and name as an ARRAY, like
<?php
$recipients = array(
'person1#domain.com' => 'Person One',
'person2#domain.com' => 'Person Two',
// ..
);
foreach($recipients as $email => $name)
{
$mail->AddCC($email, $name);
}
(or)
foreach($recipients as $email => $name)
{
$mail->AddAddress($email, $name);
}
?>
i think this may help you to resolve your problem.
I think you've got organizational problems here.
I recommend:
Set your settings (SMTP, user, pass)
Create new email object with info from an array holding messages and to addresses
Send email
Goto step 2