There are already many questions about it, but the answers I found are not clear or contrasting, while the problem, even if stated in many ways, seem IMHO to be a general one (and I have it too).
When you have hundreds to thousands recipients for your email (usually with attachments), which is the best way to follow?
I am using AddBcc (see my code above) but I've met many issues during the year, because many recipients find the mail in the spam, many simply do not receive it (or so they say), many have issues with attachments and so on.
Here the suggestion seem to use a single email with as many AddBcc as the recipients, but here we see that "SMTP RFC (RFC 5321) does not impose any limit on BCC field length, though some ISP may limit it intentionally to prevent spamming." and we find a suggestion to send one mail for recipient.
On the other hand here we find that "I'm pretty sure it's actually built into the email protocol that you can't detect which are successful. Otherwise, this information could be used maliciously to discover email addresses for spamming purposes.", so what can I do to ensure everybody to get their email?
Moreover, here we see someone strongly suggesting one email for recipient, pointing out to the PHPmailer wiki article on sending to lists
which says (amongst other interesting things) "If the messages you send are absolutely identical, you can add all the addressees using addBCC(), which will mean you only need to send() a single message, though most mail servers will have a limit on the number of addresses you can send at once."
So, if there is no theoretical limit to Bcc number, but "some" mail servers "may" have a limit on that number, and we cannot even know which email arrived and which not, focusing on reliability, what should I do?
<?php
// database connection and session init
require 'main.php';
//mailer init
require 'phpmailer/PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->setFrom('myadd#mysite.gov.it');
//query
$q="SELECT email FROM ".$genitori_table.",".$users_table." WHERE cf_g is not null";
$q=$q." AND ".$users_table.".id_g1=".$genitori_table.".id AND ".$users_table.".stato=1";
while($row = $retval->fetch_array()){
echo $row['email'];
$mail->AddBCC($row['email']);
//$mail->addAddress($row['email']);
}
$mail->isHTML(true);
$mail->Subject = 'my subject';
$mail->Body = 'my body';
$mail->AltBody = 'my alt body.';
$mail->AddAttachment('LetteraAiGenitori.pdf','lettera');
$mail->AddAttachment('AutorizzazioneUscitaAutonomaAlunni.pdf');
if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent';
}
?>
Related
I don't use PHP that often but when I do and I need to write a function to send E-Mails, I just used the mail() function. I have used it on a shared hosting service and I always received the E-Mails from a... well... not an account? A bot? It didn't even have an E-Mail address.
And that's what I want to achieve at this very moment - send an E-Mail to me without really connecting to a SMTP server or going through authentication. How can be that done with PHPMailer? Is it even possible in my case? And if you somehow got my question, how are such E-Mails even called; the ones that... aren't sent by... well... an E-Mail account?
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'PHPMailer-master\src\Exception.php';
require 'PHPMailer-master\src\PHPMailer.php';
require 'PHPMailer-master\src\SMTP.php';
$mail = new PHPMailer();
$mail->FromName = "A random name";
$mail->addAddress("myemail#gmail.com", "Recepient Name");
$mail->isHTML(true);
$mail->Subject = "Subject is here";
$mail->Body = "Hello, <br>test body ";
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message has been sent";
}
?>
This did make me laugh a bit...
No, emails can't just magically spring into existence, but there isn't necessarily a direct correlation between email user accounts and addresses.
When you send from a shared hosting account by calling mail(), the mail server knows the account you're sending from, and sometimes doesn't require authentication as a result. This for example is how GoDaddy operates. Unfortunately this approach is very prone to abuse because there is often little preventing you from flat-out lying about who you are. This is why such services are usually a) terrible and b) extremely unreliable for actually delivering messages.
If you don't specify a "from" address, the server will usually make one up from information it does have – typically your user account name, or the name of the user running the script (e.g. www-data), and the hostname of the server you're on, often something like randomnumber.hostingprovider.example.com. Look at the headers of messages you've sent before, and you'll probably see something like that.
Sometimes this address can be the same for all users on a given shared server, so your delivery reputation can depend on what others are sending, which could well be spam, phishing, malware, etc.
This vagueness is terrible for deliverability, so if you host your contact form on such a system, expect messages from it to end up in a spam folder.
If you use SMTP to send via a "proper" account you gain a lot more control and reliability, but unfortunately some hosting providers (GoDaddy again) block outbound SMTP and force you to use their mail servers. This is a way of saying that if you want to send email that will be delivered, use a decent hosting provider.
Once you get control over your sending, you can choose exactly what addresses messages are sent from, subject to authentication constraints including things like SPF, DKIM, and DMARC, but that's another story.
To my knowledge it is possible and have it work correctly each time. In the last year I found that the e-mails I sent using the mail() function would immediately go into my spam box (as well as the junk box of others) causing great confusion. I upgraded to PHPMailer to solve this and I have never set it up to use SMTP and works just fine.
The code I have is:
$mail = new PHPMailer(true);
$html = $email->get(); // This gets a standard HTML Template to use as the base of the e-mail.
$title = 'Title for Inside the HTML';
$subject = 'The E-mail Subject';
$html = str_replace('[title]',$title,$html); //Use this to replace the [title] element in my HTML Template with $title.
$html = str_replace('[date]',date("F j, Y g:i A"),$html); // Again, replaces [date] in the HTML Template with the current date and time.
$body = 'Hello My Good Friend,<br>This is just a simple <strong>HTML Message</strong><br><br>Thank you.';
$html = str_replace('[body]',$body,$html); //Add my HTML Message to the HTML Template.
try {
//Recipients
$mail->setFrom('noreply#example.com', 'My Organization');
$mail->addAddress($row["email"], $row["fullname"]); // Add a recipient
//Content
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = $subject;
$mail->Body = $html;
$mail->AltBody = strip_tags($html,'<br>');
$mail->send();
//Return Success Message
$rMsg .= '<div class="alert alert-success">
<strong>Success: </strong> We have e-mailed the warning.</div>';
} catch (Exception $e) {
$rMsg .= '<div class="alert alert-danger">
<strong>Error: </strong> There was an error e-mailing the warning.</div>';
}
I have a simple PHP endpoint that takes a POST request and uses PHPMailer to send me an email. The whole thing works fine but I notice that in my email client (Gmail on web), the emails I receive from it seem to be grouped as part of the same thread/conversation.
Is there a param I can set in the email header to inform email clients that each message should be treated as its own separate conversation? In other words, don't chain the emails (as shown in the screenshot).
I assume this behavior can be achieved since you can effectively do this if you were sending separate emails to someone manually (versus replying to an email chain you already sent).
Here is how I send an email (simplified and redacted):
<?php
require '../utils/phpmailer/vendor/autoload.php';
$email = $_POST['email'];
$message = $_POST['message'];
$mailer = new PHPMailer;
$mailer->isSMTP();
$mailer->Host = 'smtp.mailgun.org';
$mailer->SMTPAuth = true;
$mailer->Username = getenv('MAILGUN_SMTP_USERNAME');
$mailer->Password = getenv('MAILGUN_SMTP_PASSWORD');
$mailer->SMTPSecure = 'tls';
$mailer->Port = 587;
$mailer->From = 'noreply#mydomain.com';
$mailer->addAddress('myemail#gmail.com', 'Me');
$mailer->isHTML(true);
$mailer->Subject = 'Message from Endpoint';
$mailer->Body = 'Received a message from '.$email.'. Message: '.$message;
if (!$mailer->send()) {
die('failed');
} else {
echo 'success';
}
?>
Screenshot from my email client showing messages being chained together as the same "conversation":
No, there is not.
There is a whole chunk of email RFCs relating to connecting messages together in threads: the Message-ID, In-Reply-To, and References headers. Unfortunately widespread incompetence and broken implementations have made a bit of a mess of them in practice, and so mail clients (such as gmail) sometimes resort to linking messages together by home-grown heuristics, e.g. if they are from the same sender, or happen have the same subject, even if those messages are completely unrelated in any sensible way.
What's worse, some have taken up ignoring correctly set headers, which doesn't help anyone.
Client-specific heuristics are by definition outside of the email spec, and are thus uncontrollable from the sender's point of view. Gmail is particularly poor at this, and randomly links together all kinds of unrelated messages.
While I'm here, this looks very suspicious:
require '../utils/phpmailer/vendor/autoload.php';
Your vendor folder should belong to your project, not any library used by it. Using an autoloader generated from PHPMailer's own composer.json (which is what this line looks like) is likely to include dev dependencies, which should not be present in production.
I'm a newbie in PHP. My goal is to send an email to the user registered in my system.
Here is my code:
$msg= " Hi $gen./$lName, copy and paste this code in order to activate
your account copy and paste this code:$num" ;
$email = "$emailadd";
$name= "GoodFaith Network Marketing Inc.";
$subject = "Account Activation";
$message = wordwrap($msg,70) ;
$sender = "cjoveric#myalphaedge.com";
$mail_header="From: ".$name."<". $sender. ">\r\n";
$sendmail=mail($email, $subject,$message, $mail_header );
I was able to send an email, but my problem is I want to know if the user's email address exists in Yahoo, GMail or other mail services.
Is there any way I could filter out invalid emails?
Use SMTP mail the best and easy to use SMTP.
$mail->IsHTML(true);
$mail->From="admin#example.com";
$mail->FromName="Example.com";
$mail->Sender=$from; // indicates ReturnPath header
$mail->AddReplyTo($from, $from_name); // indicates ReplyTo headers
$mail->AddCC('cc#phpgang.com.com', 'CC: to phpgang.com');
$mail->Subject = $subject;
$mail->Body = $body;
$mail->AddAddress($to);
if(!$mail->Send())
{
$error = 'Mail error: '.$mail->ErrorInfo;
return true;
}
else
{
$error = 'Message sent!';
return false;
}
Not really. About the best you can do is send an email and see if the user responds to it.
Doing a regex check on email address can be frustrating for some users, depending on regex. So, I recommend to skip your regex test and just send the verification email with a confirmation link -- anything else will leave your application brittle and subject to breakage as soon as someone comes up with a new DNS or SMTP extension. It's best to get that dealt with when their paying attention.
For example:
-a confirmation code that needs to be filled in your website
-a link, going to your website, that needs to be visited
And still it is uncertain whether the email is existing afterwards, as it is easy to simply create a temporary email to pass the validation and delete it afterwards.
Instead of validating email addresses you can use the Google API to let your users sign in using their account. It is also possible to use OpenID on a similar way. Though, even this is not 100% perfect. But heay, nothing is 100%. We all try to make is work as we want as much as possible. That's it.
PS: ICANN is expected to approve UNICODE domain names Real Soon Now. That will play merry hell with Regex patterns for email addresses.
I've just updated a contact form to use PHPMailer to stop emails being marked as junk, with no luck.
It's a fairly straight forward setup I'm using but its still going into peoples junk mail.
Here is my script, I was wondering if anyone could tell what was wrong?
include_once('../inc/phpmailer/class.phpmailer.php');
$mail = new PHPMailer();
$name = $_POST['name'];
$email = $_POST['email'];
$body = "Name: ".$name."\r\n";
$body .= "Email: ".$email."\r\n";
$body .= "Message: ".$_POST['message'];
$mail->From = "mailer#blah.com";
$mail->FromName = "Contact BLah";
$mail->Subject = "Contact From: Blah";
$mail->Body = $body;
$mail->AddAddress("john#blah.com", "john");
$mail->AddAddress("david#blah.com", "david");
if(!$mail->Send()) {
$errorMsg .= "Error sending message, please try again later.";
} else {
$errorMsg .= "Message Sent successfully.";
}
I thought that PHPmailer normally takes care of inserting proper headers?
Any thoughts?
EDIT: Added spam score
-Spam-Status: "score=0.0 tests=none version=3.1.7 cmae=v=1.0 c=1 a=8nJEP1OIZ-IA:10
a=soyWjZv28gkhNSke5wm04A==:17 a=fqdOs_Nl9wd82e3SDigA:9 a=l-lynuxnH-gfU2bevBoA:7
a=wPNLvfGTeEIA:10 a=nymK5Bb5l1cA:10 a=_6wjLm_vFSYA:10 xcat=Undefined/Undefined"
X-Spam-Level: *
EDIT 2: I just tried the script on a different server from the clients and it has the same result. Do I have to send through the SMTP setup for it not to be classed as spam?
Some reasons your mail can get marked spam:
You're sending spam
Your IP, or a block of IPs surrounding your IP has been marked as a spam source on one or more blackhole lists
The content of the email is triggering spam filters.
The recipient has added you to their blacklist
The recipient didn't add you to their whitelist
You're sending a mixed source mail ("From: xyz#example.com", but sending it from "someotherdomain.net")
SPF records for your server are misconfigured/not configured at all
Domain keys are misconfigured/not configured at all
etc...
PHPMailer is a tool. Consider it a hammer. The hammer may have bent the nail, but only because the wielder didn't aim right.
The only way you'll solve this problem is by examining the bounce messages (if any), and whatever showed up in the recipient's mailbox. If they receive the mail, but it goes into a spam folder, then get a copy of the mail and examine its headers. Most spam filters will put their spam score/reasoning in there.
Small hint:
add in a line like so
$mail->AddReplyTo( 'mailer#blah.com', 'Contact BLah' );
It should decrease your SPAM rating significantly.
I was having the same problem using PHPMailer, and here's what fixed the problem for me: set the Sender (this is different and distinct from the "From") to a valid email account for the domain you are sending the email from. This causes PHPMailer to properly set the "envelope-from" information so that the email passes SPF and Sender-ID validation. Without doing this, the "envelope-from" is a OS user id and server combination which will not be verifiable.
Example Code:
$mail = new PHPMailer;
$mail->From = 'from_email#domain.com';
$mail->Sender = 'sender_email#domain.com';
...
It is not necessarily PHPMailer's fault, there are several possible reasons for your server to be blacklisted. You can check here to see if this happened
I am using PHPMailer to send a confirmation email for newly registered users in my social network. But I found out most of them have ended up in user's spam list. (Hotmail and Yahoo). How to avoid this?
This is my script
$mail=new PHPMailer();
$mail->IsSMTP();
$mail->SMTPAuth = mSMTPAuth();
$mail->SMTPSecure = mSMTPSecure();
$mail->Host = mHost();
$mail->Port = mPort();
$mail->Username = mUsername();
$mail->Password = mPassword();
$mail->From = mFrom();
$mail->FromName = "SiteName";
$mail->Subject = "SiteName New Account Activation";
$mail->IsHTML(true);
$mail->WordWrap = 50;
$mail->Body = "<h2>Welcome to " .$sitename. " " .$username. "! </h2><br><br>";
$mail->Body .= "Please click on the link below to verify your email address:<br><br>";
$mail->Body .= "<a href='".$base. "verify.php?a=" .$gen_key."'>".$base. "verify.php?a=" .$gen_key."</a>";
$mail->Body .= "<br><br>Regards<br>";
$mail->AltBody = "Welcome to " .$sitename. " " .$username. "!\n\nTo verify your email address, please click on the link below:\n\n".$base. "verify.php?a=" .$gen_key;
$mail->AddAddress($email);
$mail->Send();
$mail->ClearAddresses();
To maximize the odds of your email arriving, there are three things you need to check:
Make sure the computer sending the email has a Reverse PTR record
Configure DomainKeys Identified Mail (DKIM) in your DNS and code
Set up a SenderID record in your DNS
details at:
http://www.codinghorror.com/blog/2010/04/so-youd-like-to-send-some-email-through-code.html
There's not much you can do about it. Most of those mail providers have lists of common IP addresses, hostnames, and other data that often get flagged as spam and if your emails match the criteria they automatically get filtered. All you can really do is tell your visitors to add your email address to their allow list before registering so the email will go through to their inbox.
Honestly, don't worry about it. If they see your emails are regularly being marked as 'not spam' then they'll eventually add an exception for it. Just tell users to check their spam folder if they don't see the email like every other site does. Usually if they mark it as 'not spam' in that folder it will automatically add an exception for that address so any other emails you send them will end up in their inbox.
Do you have a reverse DNS entry for the server sending the confirmation e-mails?
If not, this might be a rDNS issue. Some sites are much more likely to mark a message as SPAM if the IP and name of the sending host don't match according to rDNS.
Otherwise, you might try sending confirmation e-mails to your own accounts on major e-mail sites like yahoo, hotmail and g-mail and then tweaking the wording until it gets past the spam filters.
Hm, there is SOMETHING you can do:
* Scrap the HTML. This looks like spam, especially with low text
* Write some more text, please.
Short HTML mails may rise up quite on the spam list.
I discovered that any variation of the word "confirm" in the title ends up in my spam bucket. I found other words that also do this: "purchase", "hurry", "order", "bargain", and "imminent".
This may not be true in all emails, but it happens in mine. It may be because those words appear in most of the emails I mark as span. It also may be that a local sysop made a filter and distributed it to all of us.
You can try using sendGrid apis which will helps, they charge but I think it is worthy. They support most popular languages : Nodejs, PHP, Java, ....