How to check mail is sent or not in laravel? - php

I'm currently working on laravel mail. I've sending email structure with attachment like this:
$document = Document::find($request->document_id);
Mail::send('email.senddocs', array('project'=>$document->project->name,'type'=>$document->documentType->type), function($message) use($request,$document){
$file_name = public_path().'/documents/'.$document->project->p_key.'/'.$document->file_name;
$message->from('us#example.com', 'DDMS');
$message->to($request->email);
$message->attach($file_name);
});
I've already visited here. But, the process over there always returning success.
What I actually want is to know if mail is send or not. In my case, Mail sending can fail due to fake email like akdjbaksdjf#jhbasdhadfs.com or by some other errors occurred.
How can I know mail is sent or not ?
Any help is appreciated

This questions is asked several times here:
Laravel 5 - check if mail is send
You can use the failure method for this:
if( count(Mail::failures()) > 0 ) {
foreach(Mail::failures as $email_address) {
echo "$email_address <br />";
}
} else {
echo "Mail sent successfully!";
}
This only checks if a email was send. You can not handle not existing email adresses with this method.
You can use mailgun for this problem for example.
Another way is to use a php class which connects to a smtp server, and will check.
PHP class:
https://www.phpclasses.org/package/6650-PHP-Check-if-an-e-mail-is-valid-using-SMTP.html
Some Informationen of checking email adresses: How to check if an email address exists without sending an email?

Related

PHP / Laravel 5 - Check if email is successfully received by recipient

How do I check if the email is RECEIVED by the recipient? In Laravel 5, I try using this method from this question:
$status = Mail::send('blah', $data, function($message) {
// callback function
});
if($status) {
// email is successfully sent
}
else {
// email is not sent
}
But even if the email is invalid, I still got $status = 1 after the code execution. I also have tried Mail::failures() which contain an array of failed attempt. But it always return 0, which mean all email is succesfully sent.
Is there any other way that I can check whether in Laravel?
OR
is it possible to check if the email is valid using PHP? Since the email is invalid, there is no point to send it.
To check if someone has received put this in the header:
Disposition-Notification-To:<xxx.xxx#example.com>
But this option is not very reliable it is better to check if your email was read like so:
<img src="http://yourdomain.com/received?read=<email of `receiver>">
This method also does not always work.
For example if the Email client doesn't download the images automatically.
I hope this helped anyway and was what you were searching for.

PHPMailer returns true even if sending to fake address

I need to know if PHPMailer was unable to send an email. But even sending to a fake email address returns true:
$phpmailer = new PHPMailer( true );
$phpmailer->setFrom( "myemail#myemailladdy.com", "myemail#myemailladdy.com" );
//This is definitely not reachable
$phpmailer->addAddress( "fake#shdsabdasdiuahsdiuhaiduhasidsjdfake.com", "IJustPressedRandomKeys" );
$phpmailer->Subject = "fake";
$phpmailer->Body = "fake";
echo "Is Mail: " . $phpmailer->IsMail();
//This prints "1"
echo "Was Sent: " . $phpmailer->send();
Why is this returning 1/true?
(When the email is valid, I do recieve the emails, so PHPMailer is setup correctly)
PHPMailer does not know whether an email address is real or not. The mail server won't know until it sends the email and gets a rejection response. But the handoff between the server and PHP has already been terminated by that point.
There is no real way to verify an email address exists without sending an email to it and getting either a response or having the user enter a unique token into a web form. The closest you can get is verifying MX records or other DNS information that verifies a domain exists, etc. But that will not be perfect and will have false positives as well as letting fake emails through if the domain is valid.
I wos thinking about it for a while... and i think i have a nice solution.
If there will be some kind big trouble:
if(!$mail->Send()) {
echo $mail->ErrorInfo; // this is important for you
// other functions...
}
or if will be success?
else {
$smtp_msg = 'ALL OK'; // sets the message you want to see
if ($mail->ErrorInfo != '') { // check if there wos any other error
$smtp_msg = $mail->ErrorInfo; // if yes - show it to me
}
// else is optional but no need couse if there wos no error we already set $smtp_msg = 'ALL OK';
return $smtp_msg;
}
Or even better you could try to use codes of exrrors to show youre own messages...
Or... use try/catch like here:
Error handling with PHPMailer
This could be helpfull!

PHPMailer and multiples destination addresses issue

Im using phpmailer to send emails and i check that when i add some addresses and just one of them is an invalid address (not exists) E.G. "asdfasfasf#asdfasdfsfsfs.commm" and send the email i see that the email was sent (to correct addresses) and i have no idea how to check if one of the adresses is wrong to be able to log that issue before sending the email.
The code to send and add addresses is this:
foreach($options['emails'] as $email){
$mmail->AddAddress($email[0], $email[1]);
}
if (!$mmail->Send()) {
echo "error";
}else {
echo "sent";
}
Thanks in advance
Take a look at filter_var to validate the syntax:
if (filter_var($email[0], FILTER_VALIDATE_EMAIL)) {
// email address is considered valid
Note that there are ways to connect to the recipients SMTP server and ask if the email actually exists (see https://code.google.com/p/php-smtp-email-validation/ for example) however many email servers won't honor these queries anymore, due to spammer abuse.

Email in loop sends the same file using Email class in Codeigniter

Hey I'm using Codeigniter's Email helpers, and expiriencing a wierd issue. I have the following code :
$path = mpdf_create_billing($html);
$this->load->library('email');
$this->email->set_newline("\r\n");
$this->email->from('no-reply#foo.com');
$this->email->to("foo#gmail.com");
$this->email->subject('Invoice for '.date('d/m/y'));
$this->email->message($message);
$this->email->attach($path);
if($this->email->send())
echo "Email Sent Successfully to $email with the file $path<br>";
else
echo "Should be sending email to $email , but i didn't<br>";
Now this code is inside a foreach loop,twice in this case. mpdf_create_billing returns path to a PDF file. now this code echos 2 different file paths, but the email is the same and in both loop runs and both of the emails contain the same file, though the file paths are different.
Anyone knows how to resolve it? this is what outputs for me :
Email Sent Successfully to foo#foo.com with the file
/path/to/pdf/Invoice_1368452801.82065190eec1c85eb.pdf
Email Sent Successfully to foo#foo.com with the file
/path/to/pdf/Invoice_1368452804.53475190eec482917.pdf
Could this be a problem with my SMTP server that send the emails? I tried it on 2 mail accounts, and same result.
Perhaps you should clear $this->email?
From the CodeIgniter docs:
$this->email->clear()
Initializes all the email variables to an empty state. This function
is intended for use if you run the email sending function in a loop,
permitting the data to be reset between cycles.
foreach ($list as $name => $address)
{
$this->email->clear();
$this->email->to($address);
$this->email->from('your#example.com');
$this->email->subject('Here is your info '.$name);
$this->email->message('Hi '.$name.' Here is the info you requested.');
$this->email->send();
}
If you set the parameter to TRUE any attachments will be cleared as
well:
$this->email->clear(TRUE);
Looks to me this is what you are doing?
Link CI3: https://www.codeigniter.com/user_guide/libraries/email.html
Link CI2: https://www.codeigniter.com/userguide2/libraries/email.html

PHP e-mail to spam

I'm trying to email new registered users for email verification (PHP) but i don't get it, why would an email be sent to SPAM, i already checked out similar questions and all answers are about Headers,
It seems a bit complicated for me to get known to those headers and how are they being verified,
By sender website ? lets say i sent as user#google.com and the actual server domain is domain.com, how would it know? and is it one of the main reasons why it goes to spam ?
I am using VPS, does it has anything to do with it ?
I'm just trying to understand the clear/simple reasons of why would an email be checked as spam
and what if i sent from the server IP and not the domain itself
Most of the mail servers will do Reverse DNS lookup to prevent people from domain.com pretending to be from otherdomain.com. It will check if the IP address from which the email was sent resolves to the same domain name of the email sender. Yahoo and other big companies will also use DKIM to verify you.
Often your message can end up in Bulk/Spam if it doesn't have much content, or if you sent a lot of the same content to one server.
Here's a good article about what web developers should know about sending email that might help you understand the subject.
1) Check headers. You could use any email sending library such as PHPMailer (http://code.google.com/a/apache-extras.org/p/phpmailer/wiki/PHPMailer#Documentation_and_Resources)
2) Check hosting server. If your is using shared hosting then most probably it has been blacklisted by the email domain.
Configure an email address on your domain, replace me#mydomain.com with your newly created email address on your domain andid#hotmailOrgmail.com with your Hotmail/Gmail id in the following script.
Also replace Your Name with your name in the following script and test it on your server:
<?php
$myName = "Your Name";
$myEmailAddressonDomain = "me#mydomain.com";
$myPreferredEmailAddresson = "id#hotmailOrgmail.com";
$mail = $_POST['email_field'];
$clientName = $_POST['name_field'];
$subject = $_POST['subject_field'];
$text = $_POST['message_field'];
$headers = 'From: "$name" <$yourEmailAddressonDomain>'.PHP_EOL.'Reply-To: '.$_POST['mail'].PHP_EOL;
$to = '"$yourname" <$myPreferredEmailAddresson>';
$message = $text.PHP_EOL.PHP_EOL."---".PHP_EOL."From: ".$name." <".$mail.">";
/* Server-side form validations */
$err = "Error with ";
if (!checkLen($name)) {
$err.='Name';
} else if (!checkLen($mail) && !checkEmail($mail)) {
$err.='Email';
} else if (!checkLen($subject)) {
$err.='Subject';
} else if (!checkLen($text)) {
$err.='Message';
}
if (strlen($err)>11) {
echo $err.' field';
exit;
}
/* end validations */
elseif (mail($to, $subject,$message, $headers)) {
echo "<span style='color: #336600'>Your message has been sent.</span>";
} else {
echo "An error occurred, please try again.";
}
function checkLen($str,$len=1)
{
return isset($str) && mb_strlen(strip_tags($str),"utf-8") > $len;
}
function checkEmail($str)
{
return preg_match("/^[\.A-z0-9_\-\+]+[#][A-z0-9_\-]+([.][A-z0-9_\-]+)+[A-z]{1,4}$/", $str);
}
?>
The email will land on your Hotmail/Gmail inbox (or any non-spam) folder via your domain's email address.
Note: Clicking Reply in the received email would show you the client's email address (as we have set in Reply-To header above)
Make appropriate changes and you are good to go.
as you are operating VPS, you may consider setting up DKIM and SPF on your server, they are used by mail services like Gmail to classify your server as a legitimate server.

Categories