PHP sending an HTML EMAIL Page from a website - php

I've used PHP to send emails before but never to send a full HTML page from another source and so I'm wondering where to start and a few other things.
I did a bit of research but my confusion isn't clearing up any.
Do I directly get the web-page contents and send that or can I use a setting to just use a URL?
What is the simplest method I could use and could someone show me an example?
Are there risks with sending an email like this to say... 5000 people and how do I change the header data with a return link to URL source?

The following line get the contents of a HTML page.
$mail->MsgHTML(file_get_contents('contents.html'));
Go here for full details:
http://phpmailer.worxware.com/index.php?pg=exampleagmail
require_once('../class.phpmailer.php');
//include("class.smtp.php"); // optional, gets called from within class.phpmailer.php if not already loaded
$mail = new PHPMailer(true); // the true param means it will throw exceptions on errors, which we need to catch
$mail->IsSMTP(); // telling the class to use SMTP
try {
$mail->Host = "mail.yourdomain.com"; // SMTP server
$mail->SMTPDebug = 2; // enables SMTP debug information (for testing)
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->SMTPSecure = "tls"; // sets the prefix to the servier
$mail->Host = "smtp.gmail.com"; // sets GMAIL as the SMTP server
$mail->Port = 587; // set the SMTP port for the GMAIL server
$mail->Username = "yourusername#gmail.com"; // GMAIL username
$mail->Password = "yourpassword"; // GMAIL password
$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!
}

Disclaimer: I can't yet comment, so please forgive this being an "answer".
I think you're probably going to have to clarify your objectives a little bit here.
It sounds like what you want to do is first build a basic scraper unless you have access to the raw html file.
Basically you can use fopen("Url", "r"), fsockopen("url", 80), or use a curl handler to submit the page request.
From here, depending on your method, you would read the response and generate an HTML or multi-part e-mail.
As far as adding a link to the e-mail header, you can do that, but I have a feeling it's not going to do what you want it to. The way to do it will depend on how you decide to send the e-mail.

Ives' answer is nice.
There is one gotcha you really want to consider with emailing an html page.
Html emails and Html pages are two totally different school.
Html emails take you back 10 years (hello tables!) in what you can do to support as many email clients as possible.
It's very likely a straight email-a-webpage thing will look total crap on the recipient email..
and then you've got to consider embedding stylesheets, etc..

Related

PHP Mailer sending duplicate emails

So as the title implies
Im trying to send an email (one email) but the problem I'm facing is bizarre.
Whenever debug is turned on, email is sent only once.
But when debug is turned off, around 3 to 4 emails are sent at once.
NOTE: I'm using localhost not an actual server.
to diagnose the problem, I did the following:
1- used a md5 to generate random string in the "subject" to check whether email is sent with same contents or different. and the results were totally different. meaning, emails weren't duplicate but actually being sent couple of times.
2- opened the project in a browser with no extensions to make sure the problem wasn't in an extension loading my project page more than once. and the results were also similar to number 1, different "subject" also.
so, long story shot. i have no idea what causes this problem to happen. and why it only stop happening when debug is turned on.
NOTE: this is not my first time to use PHP mailer, but my first time to face this problem. I'm also using the latest version of PHP mailer (6.5.1)
Here is my entire code:
in PHP mailer file:
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\SMTP;
require ABSPATH.'inc/phpmailer/script/src/PHPMailer.php';
require ABSPATH.'inc/phpmailer/script/src/Exception.php';
require ABSPATH.'inc/phpmailer/script/src/SMTP.php';
function SendEmail(){
$mail = new PHPMailer(true);
try {
//Server settings
$mail->SMTPDebug = SMTP::DEBUG_OFF;
$mail->SMTPAuth = true;
$mail->SMTPSecure = 'ssl';
$mail->isSMTP();
$mail->Host = '*****';
$mail->SMTPAuth = true;
$mail->Username = '*****';
$mail->Password = '*****';
$mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
$mail->Port = 465;
$mail->SMTPAutoTLS = false;
$mail->SMTPOptions = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
)
);
$mail->ClearAllRecipients();
$mail->clearAttachments();
//Recipients
$mail->setFrom('*****', '******');
$mail->addAddress('*******', '*****');
$mail->addReplyTo('******', '******');
//Attachments
$mail->addAttachment(ABSPATH.'upload/dog.jpg', 'new.jpg');
//Content
$mail->isHTML(true);
$mail->Subject = md5(rand()); //This is how I'm checking whether it sends same email with same subject header or different ones. and it does send different ones
$mail->Body = 'This is the HTML message body <b>in bold!</b>'. md5(rand());
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!";
$mail->ContentType = 'text/html; charset=utf-8\r\n';
$mail->send();
echo 'Message has been sent';
} catch (Exception $e) {
echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
}
and here is the file I'm using to call the function
<?PHP
// NO LOOP here
require_once(ABSPATH.'inc/phpmailer/phpmailer.php');
SendEmail();
As always, the first place to check is the docs.
Since you've already tried the random hash in the subject trick (well done on your logic!), you know that the problem is not that your script is sending more than one message, but that your script is being called repeatedly, and you should see evidence of that in your web server logs too. The usual reason for this is browser extensions which have a nasty habit of doing multiple submissions. Test that by using a clean browser with no extensions (e.g. use a browser you don't normally use, like Opera, Brave, or Chrome Canary).
Any requests that your browser is making should appear in the network tab of the dev console. On the server side you can either set up remote debugging to trigger breakpoints (tricky), or var_dump every request to a log so you get full details of what's calling the script.
BTW, you really shouldn't be disabling TLS verification. Fix the problem properly instead of hiding it; the troubleshooting guide has lots on that subject.
I had the same issue and solved by upgrading to the latest version of PHPMailer.

How to know mail is send and read by user when sending mail using SMTP,PHPmailer

is anybody know any solution for below problem
in my project, i am send email to client using smtp and php mailer and gmail script. so when i am send mail gmail send mail to particular client. for that i am passing gmail login and user name which is valid. all mail are sending properly. but sometime it may happen that some client not receive mail and at that time i am not able to get or trace any error. so i there any way, when i am sending mail to client , and when client get it and read it at that time i got any kind of confirmation.
Please if anybody have any idea , help me out.
<?php
/**
* Simple example script using PHPMailer with exceptions enabled
* #package phpmailer
* #version $Id$
*/
require ('../class.phpmailer.php');
try {
$mail = new PHPMailer(true); //New instance, with exceptions enabled
$body = "Please return read receipt to me.";
$body = preg_replace('/\\\\/','', $body); //Strip backslashes
$mail->IsSMTP(); // tell the class to use SMTP
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->Port = 25; // set the SMTP server port
$mail->Host = "SMTP SERVER IP/DOMAIN"; // SMTP server
$mail->Username = "EMAIL USER ACCOUNT"; // SMTP server username
$mail->Password = "EMAIL USER PASSWORD"; // SMTP server password
$mail->IsSendmail(); // tell the class to use Sendmail
$mail->AddReplyTo("someone#something.com","SOMEONE");
$mail->From = "someone#something.com";
$mail->FromName = "SOMEONE";
$to = "other#something.com";
$mail->AddAddress($to);
$mail->Subject = "First PHPMailer Message[Test Read Receipt]";
$mail->ConfirmReadingTo = "someone#something.com"; //this is the command to request for read receipt. The read receipt email will send to the email address.
$mail->AltBody = "Please return read receipt to me."; // optional, comment out and test
$mail->WordWrap = 80; // set word wrap
$mail->MsgHTML($body);
$mail->IsHTML(true); // send as HTML
$mail->Send();
echo 'Message has been sent.';
} catch (phpmailerException $e) {
echo $e->errorMessage();
}
?>
Some modification need to be done in above script.
Configure SMTP mail server.
Set the correct FROM & FROM Name (someone#something.com, SOMEONE)
Set the correct TO address
from
also
Delivery reports and read receipts in PHP mail
You can always add reply to mail address which will take care if there is any error so you will get email back, and for if it's read, include a picture (blank picture of 1 pixel will do) and add code in that picture like and you can see how many hits that image did recieve or recieved any at all.
You can check that things in two different ways like, by using the header "Disposition-Notification-To" to your mail function, it will not going to work in all case because most people choose not to send read receipts. If you could, from your server, influence whether or not this happened, a spammer could easily identify active and inactive email addresses quite easily.
You can set header like
$email_header .= "Disposition-Notification-To: $from";
$email_header .= "X-Confirm-Reading-To: $from";
now the another method to check is by placing an image and you can add a script to onload of that image, that script will send notification to your system that xxx user have read the mail so, in that way you can track delivery status of the mail.
In fact, I can't think of any way to confirm it's been delivered without also checking it gets read, either by including a image that is requested from your server and logged as having been accessed, or a link that the user must visit to see the full content of the message.
Neither are guaranteed (not all email clients will display images or use HTML) and not all 'delivered' messages will be read.
Though for more info https://en.wikipedia.org/wiki/Email_tracking

Sending a mail with php: Script is waiting for the answer?

I am using the class PHPMailer to send Mails via SMTP:
<?php
require 'php_mailer/class.phpmailer.php';
$mail = new PHPMailer;
$mail->IsSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp.dfgdfgdfg.de'; // Specify main and backup server
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'dfgdfg'; // SMTP username
$mail->Password = 'dfgsdfgdsfg'; // SMTP password
//$mail->SMTPSecure = 'tls'; // Enable encryption, 'ssl' also accepted
$mail->From = 'community#fdgdfg.de';
$mail->FromName = 'dfgdfgdg';
$mail->AddAddress('interview#dfgdfg.de', 'Udo'); // Add a recipient
$mail->AddBCC('bcc#example.com');
$mail->WordWrap = 50; // Set word wrap to 50 characters
$mail->IsHTML(true); // Set email format to HTML
$mail->Subject = 'HTML-Mail mit Logo';
$mail->Body = 'Nachfolgend das <b>Logo</b>';
$mail->AltBody = 'Aktiviere HTML, damit das Logo angezeigt wird';
if(!$mail->Send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
exit;
}
?>
My Questions:
Whats the best way to send to a lot of Mails (same Mailtext, only the appellation is different (Hello $NAME)?
Is the PHP script waiting until every mail is delivered? Because sometimes I want to send a mail to some hundreds people, when a user is doing an action on the website. so this user cant wait of course, until all those mail were sent succesful!
Thanks!
Alex
You are setting PHPMailer to interact with SMTP, so I guess that it will wait for it to complete. This is not optimal, because as you say you will block the PHP script until SMTP responds.
It would be better to send through your localhost: set PHPMailer to use sendmail, which will usually be a wrapper to a local exim4 or postfix, which will then handle the mailing for you. This is much better, also because the local server will handle any possible temporary error, and retry later. PHP won't.
You may also want to explore other options, like Mandrill or Sendgrid to do the job, especially if you do lot of mailing or bulk mailing.
Whats the best way to send to a lot of Mails (same Mailtext, only the
appellation is different (Hello $NAME)?
You can do something like, Set the name too.
// rest of code first
$mail->AddAddress("you#example.com")
$ids = mysql_query($select, $connection) or die(mysql_error());
while ($row = mysql_fetch_row($ids)) {
$mail->AddBCC($row[0]);
}
$mail->Send();//Sends the email
You can have special string 'name_here' in the body and place $name with str_replace function
Is the PHP script waiting until every mail is delivered? Because sometimes I want to send a mail to some hundreds people, when a user is doing an action on the website. so this user cant wait of course, until all those mail were sent succesful!
Yes according to my knowledge you will have to wait.
How to do a str_replace ? Assume that your email body is as follows
$body = " Dear %first_name%,
other stuff goes here....... ";
$body = str_replace("%first_name%", $first_name, $body);
above will replace %first_name% with the name($first_name) you provide.

PHPMailer Mailer Error: Message body empty

I'm trying to get the basic example working for PHPMailer.
All I done was upload the whole PHPMailer_5.2.2 folder, configured the page below as per the code you see and I keep getting Mailer Error: Message body empty, but I can clearly see the contents.html file has html in it and isn't empty. This is the example file I'm using from the PHPMailer PHPMailer_5.2.2/examples/test_smtp_gmail_basic.php
I tried using the settings I have in Outlook for Gmail that works, I know my username and password, the SMTP port is 587 and it's set to TLS, I tried replacing SSL with TLS in the code below, I still get same error.
I also tried the following code, which has been suggested:
changed this:
$mail->MsgHTML($body);
to this
$mail->body = $body;
I still got same error, is there something else I need to configure? It's my first time using PHPMailer, I can get the standard php mail working, but I want to try this because the page I'm going to be emailing has lots of html and I don't want to have to go through all the html and enter character escapes so someone recommending using this.
<?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 = preg_replace('/[\]/','',$body);
$mail->IsSMTP(); // telling the class to use SMTP
$mail->Host = "smtp.gmail.com"; // SMTP server
$mail->SMTPDebug = 1; // enables SMTP debug information (for testing)
// 1 = errors and messages
// 2 = messages only
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->SMTPSecure = "ssl"; // sets the prefix to the servier
$mail->Host = "smtp.gmail.com"; // sets GMAIL as the SMTP server
$mail->Port = 587; // set the SMTP port for the GMAIL server
$mail->Username = "xxx#gmail.com"; // GMAIL username
$mail->Password = "xxx"; // GMAIL password
$mail->SetFrom('xxx#gmail.com', 'First Last');
$mail->AddReplyTo("xxx","First Last");
$mail->Subject = "PHPMailer Test Subject via smtp (Gmail), basic";
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
$mail->MsgHTML($body);
$address = "xxx.net";
$mail->AddAddress($address, "John Doe");
//$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!";
}
?>
I had the same problem and I solved just changing:
This:
$mail->body = 'Hello, this is my message.';
Into this:
$mail->Body = 'Hello, this is my message.';
body into Body what a little mistake!
PHPMailer->MsgHTML() tries to do something clever with fixing non-absolute URLs, but for me too it just returns empty.
$mail->IsHTML(true);
$mail->Body=$body;
First I had to enable the ssl extension, (which I have obtained from another post on this site). To do that, open php.ini and enable php_openssl.dll by changing
;extension=php_openssl.dll
to
extension=php_openssl.dll
Now, enable tls and use port 587. Then comment out the preg_replace.
Finally, I was able to make it show up in my gmail "Sent" file, although I was expecting to see it in my "Inbox".
This site is awesome! Thanks.
When setting $mail->Body equal to variable the body is empty.
When I attach a string to the body everything works fine.
The solution is to strval() a variable containing Your HTML code.
$message;//Your HTML message code
$mail->Body = strval($message);

How to send HTML emails where the signature doesn't get clipped?

I am trying to send emails through PHP and, while the messages get delivered, I'm having a small issue. In Gmail, and probably other email clients, the last line of the message (the signature) is getting clipped. By "clipped" I mean that the last line is hidden, with a sort of button that can be clicked to unhide the last line.
Is there some way to stop this from happening? This is my first time trying to send HTML emails through PHP, so I thought maybe there's some kind of syntax I don't know about.
I'm basically just using the phpmailer example code:
require_once('../class.phpmailer.php');
//include("class.smtp.php"); // optional, gets called from within class.phpmailer.php if not already loaded
$mail = new PHPMailer(true); // the true param means it will throw exceptions on errors, which we need to catch
$mail->IsSMTP(); // telling the class to use SMTP
try {
$mail->Host = "mail.yourdomain.com"; // SMTP server
$mail->SMTPDebug = 2; // enables SMTP debug information (for testing)
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->SMTPSecure = "tls"; // sets the prefix to the servier
$mail->Host = "smtp.gmail.com"; // sets GMAIL as the SMTP server
$mail->Port = 587; // set the SMTP port for the GMAIL server
$mail->Username = "yourusername#gmail.com"; // GMAIL username
$mail->Password = "yourpassword"; // GMAIL password
$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<p></p>\n";
} catch (phpmailerException $e) {
echo $e->errorMessage(); //Pretty error messages from PHPMailer
} catch (Exception $e) {
echo $e->getMessage(); //Boring error messages from anything else!
}
Appreciate your advice.
No, there isn't really. The "clipping" as you refer to it is done by GMail (or whatever client) based on its own analysis of the content of the email - if something looks like a signature/quoted reply, it'll collapse it.
It has nothing to do with how you're sending the email.
Solution often repeated on SO is to eliminate any sort of "repetition" so people add unique timestamps in the footer, invisible images etc.
In my case Gmail exhibited a bug and would display this message because the first name was appearing inside the subject line and inside the body of the email.
And it wasn't even trimming the message, it was displaying the full message, but saying that it's trimmed.
Solution is to try to manually cut out chunks of the email and keep sending yourself tests until you stop seeing the notice and then work your way out from there.

Categories