How to get current email id in body using PHP Mailer - php

Currently I am working on a PHP email script using PHPMailer` library. I am sending a mass mail using BCC for all the email addresses.
I want each email to contain the current recipient's email address in the message body.
Below is my sample code:
<?php
require 'PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->isSMTP();
$mail->Host = 'smtp1.example.com;smtp2.example.com';
$mail->SMTPAuth = true;
$mail->Username = 'user#example.com';
$mail->Password = 'secret';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
$mail->setFrom('from#example.com', 'Mailer');
$mail->addAddress('noreply#example.com');
$arrMail [] = array('bcc1#example.com','bcc2#example.com');
for($i=0;$i<count( $arrMail);$i++)
{
$mail->addBCC($arrMail[$i]);
$htmlversion = 'Hello '.$arrMail[$i].' !'.
}
// $htmlversion = 'Hello <email_id needed here> !'.
$mail->Body = $htmlversion;
$mail->AltBody = $textVersion;
if(!$mail->send())
{
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
}
else
{
echo 'Mail sent';
}
Problem: If bcc1#example.com receives the email, its message body should contain their email address. Currently I am getting the first email address in the message body for every recipient.
Note: I dont want to send mail one-by-one using To like mentioned in other pages.
Also is it possible by using some session or database logic?
I am using php 5.5.9.

Your code is reusing the same email address because you didn't put the creation of the mail body in the loop. If you use a loop then you also don't need BCC.
$arrMail [] = array('bcc1#example.com', 'bcc2#example.com');
$total = count($arrMail);
for($i = 0; $i < $total; $i++) {
$email = $arrMail[$i];
$htmlversion = "Hello $email !";
$mail->Body = $htmlversion;
$mail->AltBody = $textVersion;
$mail->AddAddress($email);
if (!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'Mail sent';
}
}
I dont want to send mail one-by-one using To like mentioned in other pages.
Unfortunately, BCC by its very nature sends the same email to multiple recipients. If you want to customise each email for each person, you have to send them individual emails.

Related

How Sending multiple emails with PHPmailer

I have thousands of emails and I want to send an e-mail to all of them and I can not solve it. Is anyone able to help and clarify with examples in ways of solving
As shown in the following code what is the problem and what is the solution
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'gator4164.hostgator.com '; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = "..."; // SMTP username
$mail->Password = '...'; // SMTP password
$mail->SMTPSecure = 'ssl'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 465; // TCP port to connect to
$mail->CharSet = 'UTF-8';
$get = new get();
$getEmails = $get->getEmails();
$CountEmails = $get->CountEmails();
$mail->setFrom('email#gmail.com', 'Email Name');
foreach($getEmails as $getEmails){
for ($x = $emails['id']; $x <= $CountEmails; $x++) {
$mail->addAddress($emails['email'],$emails['name']);
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = $title;
$mail->Body = nl2br($content);
$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'<div class="done">Done</div>';
}
}
For such kind of scenario, you have to create a Process Queue because every email sending needs some time to process and if the email count is thousand then in that case your system will crash as it is having a processing time limit. For creating a process queue you have to maintain a database table in which save all the records and maintain a status with different values like:
0: Initial, 1:Processing, 2: Email Sent
And create a separate functionality that pick a record on a regular interval and send the email and change the status. Put this functionality on CRON.
Don't add all of the recipients with "add" in one loop then you have one Email with all recipients. Send your E-Mail with every duration.
foreach($getEmails as $getEmails){
$emails['email'] = $getEmails['email'];
$emails['name'] = $getEmails['name'];
$mail->addAddress($emails['email'],$emails['name']);
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = $title;
$mail->Body = nl2br($content);
$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'Email send to ' + $emails['email'];
}
$mail->clearAddresses();
}
something like this. So send the Email for every duration. To prevent that you send people duplicate emails you should set the status in your database if the email is send otherwise you send it again if you have an error in your script and you have to restart the script.

How can I send a confirmation mail to an email ID from local host without a domain name?

Once my code is run in PHP, it says that the confirmation mail has been sent successfully, but the mail has not been received at the target mail ID. I have used the mail() function in PHP to send the confirmation mail and I have also installed Postfix on my Ubuntu. What is the problem here?
<?php
include('config.php');
$tb_name = temp_members_db;
$confirm_code = md5(uniqid(rand()));
$name = $_POST['name'];
$email = $_POST['email'];
$pass = $_POST['pass'];
$country = $_POST['country'];
$sql = "INSERT INTO $tb_name(confirm_code,name,email,password,country) VALUES ('$confirm_code','$name','$email','$pass','$country')";
$result = mysql_query($sql);
if($result) {
$to = $email;
$sub = "Your Confirmation Code";
$message = "Your confirmation code is" . $confirm_code;
$send = mail($to,$sub,$message);
var_export($send);
} else {
echo "Havent found email ID in our database";
}
if($send) {
echo "Sent the confirmation link to your email ID";
} else {
echo "Sending failed";
}
?>
Have you switched on the SMTP function on the localhost server?
If not enabled the SMTP and mail functions
Use PHPMailer class. Very easy to install and use. The PHP mail() function usually sends via a local mail server, typically fronted by a sendmail binary on Linux, BSD and OS X platforms, however, Windows usually doesn't include a local mail server; PHPMailer's integrated SMTP implementation allows email sending on Windows platforms without a local mail server.
Just download the class files from here: https://github.com/PHPMailer/PHPMailer
Example:
<?php
require 'PHPMailerAutoload.php';
$mail = new PHPMailer;
//$mail->SMTPDebug = 3; // Enable verbose debug output
Set SMTP and if you want to use secure encryption (ssl,tls and ports)
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp1.example.com;smtp2.example.com'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'user#example.com'; // SMTP username
$mail->Password = 'secret'; // SMTP password
$mail->SMTPSecure = 'tls'; // If you want to use encryption, `ssl` also accepted
$mail->Port = 587; // TCP port to connect to(or port 25,465 etc)
Set fields like from, to, bcc, subject, email body etc.
$mail->setFrom('from#example.com', 'Mailer');
$mail->addAddress('joe#example.net', 'Joe User'); // Add a recipient
// Name is optional
$mail->addReplyTo('info#example.com', 'Information');
$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';
}

Setting up mail server with Zoho & making own phpMail function for it

I don't know if my code is the issue or if I had configured Zoho's SMTP's settings incorrectly.
Basically I want the ability to dynamically send emails with a simple php function like for example
phpMail("to#example.com", $subject, $body, "from#example.com", "replyto#example.com");
This is my PHPMailer.php script (it sees the function and its settings)
$mail = new PHPMailer;
//$mail->SMTPDebug = 3; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp.zoho.com'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = '**REMOVED**'; // SMTP username
$mail->Password = '**REMOVED**'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 465; // TCP port to connect to
$mail->isHTML(true); // Set email format to HTML
// SYTAX: phpMail($from, $reply, $to, $subject, $body);
function phpMail($to, $subject, $body, $from = "from#example.com", $reply = "replyto#example.com") {
if (isset($from))
$mail->From = $from;
$mail->FromName = "testing";
if (isset($to))
$mail->addAddress($to);
if (isset($reply))
$mail->addReplyTo($reply);
if (isset($subject))
$mail->Subject = $subject;
if (isset($body))
$mail->Body = $body;
$mail->AltBody = $body;
if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent';
}
}
Now the issue with this is that, I'm not receiving emails nor am I receiving any errors / messages but it's also not sending me an email.
When you make a PHP function, make sure your objects aren't outside of your function.
My error wasn't that though, it was basically my own stupidity which had nothing to do with the code but more of my "form post data".
The following configuration works for me using zoho mail.
Give it a try:
$mail=new JPhpMailer;
$mail->IsSMTP();
$mail->Host='smtp.zoho.com';
// Enable this option to see deep debug info
// $mail->SMTPDebug = 4;
$mail->SMTPSecure = 'ssl';
$mail->Port='465';
$mail->SMTPAuth=true;
$mail->Username='your_email_address';
$mail->Password='your_eamil_address_password';
$mail->isHTML(true);
$mail->SetFrom('your_email_address','Your Name');
$mail->Subject='PHPMailer Test Subject via smtp, basic with authentication';
$mail->AltBody='To view the message, please use an HTML compatible email viewer!';
$mail->MsgHTML('<h1>JUST A TEST!</h1>');
$mail->AddAddress('destination_email_address','John Doe');
if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent';
}

sending confirmation email using in php

I have a php code for sending confirmation email. But how to send this email to registered user using my mail server. Example using gmail to send confirmarion email.
<?php
if(isset($_SESSION['error'])) {
header("Location: index.php");
exit;
} else {
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$com_code = md5(uniqid(rand()));
$sql2 = "INSERT INTO user (username, email, password, com_code) VALUES ('$username', '$email', '$password', '$com_code')"; $result2 = mysqli_query($mysqli,$sql2) or die(mysqli_error());
if($result2) {
$to = $email;
$subject = "Confirmation from MyName to $username";
$header = "TutsforWeb: Confirmation from TutsforWeb";
$message = "Please click the link below to verify and activate your account. rn"; $message .= "http://www.yourname.com/confirm.php?passkey=$com_code";
$sentmail = mail($to,$subject,$message,$header);
if($sentmail) {
echo "Your Confirmation link Has Been Sent To Your Email Address.";
} else {
echo "Cannot send Confirmation link to your e-mail address";
}
}
}
}
?>
If you have mail server then you follow the your mail server rules.
You can use PHPMailer and follow the rule of phpmailer function.
Fix : You have to find out whether you have installed a mail server in your server instance. This depends on server environment. You can find how to with simple web search.
Tip: If just get the response from the operation as normal your mail server is not connected. But if it's keep waiting for like 4 to 5 seconds means most of the time server is there issue is something in it.
Ubuntu - [How to install postfix][1]
Windows - [SMTP E-mail][2]
Further issues :
Once you can send the mail using php mail function but still you have give the accurate header information otherwise the mail will send to spam folder.
Wrong: $header = "TutsforWeb: Confirmation from TutsforWeb";
Correct:
$headers = 'From: webmaster#example.com' . "\r\n" .
'Reply-To: webmaster#example.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
If you want to do it gmail just refer this : Send email using the GMail SMTP server from a PHP page
You first fetch data from table where registered users are stored then you can send mail to registered users
If you have your mail servers credentials then you can use SMTP to send emails. You can also use PHPMailer which is very easy to use.
First thing is you need to install PHPMailer from above link after that use following code
`
require 'PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp.gmail.com'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'user#gmail.com'; // Your gmail username
$mail->Password = 'your_gmail_password'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587; // TCP port to connect to
$mail->From = 'from#example.com'; // from email address
$mail->FromName = 'User1'; // whatever is the name of sender
$mail->addAddress($_POST['email'], $_POST['username']); // Add a recipient
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = $subject;
$mail->Body = $message ;
if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent';
}
?>`
Download PHPMailerAutoload
link here
<?php
// When we unzipped PHPMailer, it unzipped to
// public_html/PHPMailer_5.2.0
require("lib/PHPMailer/PHPMailerAutoload.php");
$mail = new PHPMailer();
// set mailer to use SMTP
$mail->IsSMTP();
// we are setting the HOST to localhost
$mail->Host = "mail.example.com"; // specify main and backup server
$mail->SMTPAuth = true; // turn on SMTP authentication
// When sending email using PHPMailer, you need to send from a valid email address
// In this case, we setup a test email account with the following credentials:
$mail->Username = "user#gmail.com"; // SMTP username
$mail->Password = "password"; // SMTP password
$mail->From = "from#example.com";
// below we want to set the email address we will be sending our email to.
$mail->AddAddress("to#example.com", "To whom");
// set word wrap to 50 characters
$mail->WordWrap = 50;
// set email format to HTML
$mail->IsHTML(true);
$mail->Subject = "You have received feedback from your website!";
$message = "Text Message";
$mail->Body = $message;
$mail->AltBody = $message;
if(!$mail->Send())
{
echo "Message could not be sent. <p>";
echo "Mailer Error: " . $mail->ErrorInfo;
exit;
}
echo "Message has been sent";
?>

PHPMailer and Style Sheet formatting

I'm using PHPMailer to automatically send an order acknowledgement as an HTML formatted email. Everything is working as expected except that the formatting of the acknowledgement isn't correct. I included my style sheet with an 'AddAttachment' line which seems to have fixed the header of the acknowledgement form, but the rest of the form still isn't right. Has anyone run into this situation before and know what I need to do to fix it? My edited program code follows in case it'll help!
<?php
require("class.phpmailer.php");
$mail = new PHPMailer();
$mail->SMTPDebug = 0;
$mail->IsSMTP(); // telling the class to use SMTP
$mail->SMTPAuth = true;
$mail->Port = 25; // set the SMTP port
$mail->Host = "<<smtp server>>"; // SMTP server
$mail->Username = "<<username>>";
$mail->Password = "<<password>>";
$mail->From = "<<email address>>";
$mail->FromName = "<<name>>";
$mail->AddAddress("<<email address>>");
$mail->Subject = "Acknowledgement Form";
$mail->AltBody = 'To view the message, please use an HTML compatible email viewer!'; // optional - MsgHTML will create an alternate automatically
$mail->IsHTML(true);
$mail->Body = file_get_contents('<<acknowledgement form page>>');
$mail->AddAttachment('printer.css'); // attach style sheet
if(!$mail->Send()) {
echo 'Message was not sent.';
echo 'Mailer error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent.';
}
?>
You should'nt work with external CSS files in emails... Not many of the email-clients can handle that and not all of your customers use email-clients like Outlook or Thunderbird. Instead, you should disgn you html-code "90s style" :-P
e.g. <p style="width: 200px; text-align: center;">

Categories