PHPMailer DSN How to get error when address not exist - php

I use PHPMailer for PHP5/6 and i try to make script witch will send mail and get error like "550 No Such User Here".
I read about DSN, and try tips from this How to set DSN (Delivery Status Notification) for PHPMailer? topic, but it's doesnt work.
(i found functin recipient where was
return $this->sendCommand(
'RCPT TO',
'RCPT TO:<' . $toaddr . '>',
array(250, 251)
);
)
and i try change link
'RCPT TO:<' . $toaddr . '>',
to
'RCPT TO:<' . $toaddr . '> NOTIFY=SUCCESS,FAILURE ORCPT=rfc822;' . $toaddr ."" .self::CRLF,
but i doesnt work.
I was try add it by function AddCustomHeader but it fail too.
This is my code:
private function send($username, $password, $from, $nameFrom, $replay, $subject, $email) {
try {
$_ = Zend_Registry::get('Zend_Translate');
$mail = new PHPMailer(true);
$mail->IsSMTP();
$mail->SMTPDebug = 2;
$mail->SMTPAuth = true;
$mail->SMTPSecure = "tls";
$mail->Host = "smtp.gmail.com";
$mail->Port = 587;
$mail->SMTPKeepAlive = true;
$mail->Username = $username;
$mail->Password = $password;
$mail->SetFrom($from, $nameFrom);
$mail->AddReplyTo($replay, $nameFrom);
$mail->Subject = $subject;
$mail->MsgHTML($this->_content);
$mail->AddAddress($email);
// $mail->AddCustomHeader( "X-Confirm-Reading-To: development.tabi#gmail.com" );
// $mail->AddCustomHeader( "NOTIFY=SUCCESS,FAILURE ORCPT=rfc822; $email" );
// $mail->AddCustomHeader( "Disposition-Notification-To: development.tabi#gmail.com" );
// $mail->AddCustomHeader( "Return-receipt-to: development.tabi#gmail.com" );
if (!$mail->Send()) {
return array(
'status' => false,
'message' => $mail->ErrorInfo
);
} else {
return array(
'status' => true,
'message' => $_->_('__MAIL_WAS_SEND__')
);
}
} catch (Exception $e) {
return array(
'status' => false,
'message' => $e->getMessage()
);
}
catch (phpmailerException $e) {
return array(
'status' => false,
'message' => $e->getMessage()
);
}
}
In result i have need script where:
When i write real address, ex my_real_addres#gmail.com it will be send,
but when i write fake address, ex my_fake_addres_which_not_exist#gmail.com will return me code 550, or any other error.
Is there any options to do this ? becouse i need to get and save all information.

Remember, that due to spambots and e-mail verifying scripts (such as yours). Many mail servers do not send those responses.
If they did, they would be flooded by spambots that would be asking for whole their mail databases (millions of records) if those e-mails exist.
For that reason, it's disabled on most mailservers nowdays.
Sources:
Is there a way to test if an E-Mail address exists without sending a test mail?
How to check if an email address exists without sending an email?
Edit:
Basically, every of those functions can be disabled by server admin. They may even return faked info etc. It's all to make it unsusable to spammers (legit uses got to suffer from this).
There are other methods to verify if e-mail exists. Ask for reply, for delivery confirmation etc.
Some servers when message could not be delivered return you e-mail. But that's not 100% sure behaviour, since spammers could spam servers with random generated e-mails and wait for returns.
Those measures are implemented to pervent spammers with brute-force mass e-mail checks.
They could run dictionary attack against google servers and quickly create list of all existing emails.
Don't know what you want achive, if you want to check if one of your newsletter subscribers deleted e-mail or grabbed e-mail from random site and want to confirm it.
You should follow one principle: All e-mails are unverified by default. You never know if its real or not unless it's been verified by recipent by clicking link, answering etc.
By me, there should be no status as "100% does not exist" since you're unable to verify it.

Related

how to send two different email to two different email addresses using PHPMailer in php

I am trying to send two different emails to two different recipients using PHPmailer but only the second email is arriving.
My code:
/**
* This code shows settings to use when sending via Google's Gmail servers.
*/
//SMTP needs accurate times, and the PHP time zone MUST be set
//This should be done in your php.ini, but this is how to do it if you don't have access to that
date_default_timezone_set('Etc/UTC');
require 'PHPMailer/PHPMailerAutoload.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;
//Ask for HTML-friendly debug output
$mail->Debugoutput = 'html';
//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 = "olaozias#gmail.com";
//Password to use for SMTP authentication
$mail->Password = "password";
//Set who the message is to be sent from
$mail->setFrom('olaozias#gmail.com', 'Department of Information Science');
//Set an alternative reply-to address
$mail->addReplyTo('olaozias#gmail.com', 'Department of Information Science');
//Set who the message is to be sent to
$mail->addAddress($email , 'Parent');
//Set the subject line
$mail->Subject = 'Student Attendance System';
//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'), dirname(__FILE__));
//Replace the plain text body with one created manually
$mail->Body = 'Dear Parent \r\n This email is sent from the university of gondar , Department of information science to inform you that your child '. $firstname.' has been registered for semester '.$semister. ' in order to see your child attendance status and to communicate easily with our department use our attendance system. First download and install the mobile application which is attached in this email to your phone and use these login credentials to login to the system \r\n Your child Id: '.$student_no. '\r\n Password: '.$parent_pass.'\r\n Thank you for using our attendance system \r\n University of Gondar \r\n Department of Information Science ';
//Attach an image file
//$mail->addAttachment('AllCallRecorder.apk');
$mail->send();
$mail->ClearAddresses();
$mail->AddAddress($stud_email,'Student');
$mail->Subject = 'Student Attendance System';
$mail->Body = "email 2";
//send the message, check for errors
if (!$mail->Send()) {
//echo "Mailer Error: " . $mail->ErrorInfo;
echo '
<script type = "text/javascript">
alert("Mailer Error: " . $mail->ErrorInfo);
window.location = "student.php";
</script>
';
} else {
echo '
<script type = "text/javascript">
alert("student Added successfully and an Email the sent to email address provided");
window.location = "student.php";
</script>
';
//echo "Message sent!";
}
the second email is delivered successfully but the first one is not.
There are a couple of different possibilities. The fact that the second one is sending properly is a good indication that your code is working in general. Focusing on the first one, I'd suggest three things:
Add error checking to the first send() call. You have if (!$mail->Send()) {... on the second one, but you aren't checking the first one. You can use $mail->ErrorInfo as you have in a comment in the second part. (By the way, the $mail->ErrorInfo you have in the script tag will not work. Variables in single quoted strings like that will not be parsed, so you'll just get the literal string "$mail->ErrorInfo" there if there is an error.)
Add error checking to the first addAddress() call. PHPMailer will give you an error that you can check if the email address is invalid for some reason. As far as the code you've shown here, $email appears to be undefined, but so does $stud_email and you've said that one is working properly, so I assume those are both defined somewhere before the code that you've shown here, but a possible cause for this is that $email is undefined or doesn't have the value you expect it to.
The email is being sent, but not received. It's pretty easy for a message to be mis-identified as spam at multiple points between the sender and the receiver. This is more difficult to diagnose, but if you add the error checking to the first send() call and don't get any errors, you'll at least be able to rule that out as a point of failure.
you can do an array with de emails and subject.
$recipients = array(
'person1#domain.com' => 'Person One',
'person2#domain.com' => 'Person Two',
// ..
);

Sending mail using phpmailer using smpt with dkim going thru postfix

So I am using phpmailer using smpt and it is going thru postfix to send emails. When I send a email from my email it goes thru without a problem when it comes to using DKIM and DMARC. But when I send using phpmailer Im not getting a DKIM.
<?php
function send_email($to, $from_email, $from_name, $subject, $body,
$is_html=false, $attachments=null) {
global $smtp_host, $smtp_port, $smtp_user, $smtp_password;
try {
$email = new PHPMailer(true);
if ($from_email === $smtp_user) {
$email->isSMTP();
$email->Host = $smtp_host;
$email->Port = $smtp_port;
$email->SMTPAuth = true;
$email->Username = $smtp_user;
$email->Password = $smtp_password;
$email->SMTPSecure = 'tls';
}
$email->CharSet = 'UTF-8';
$email->From = $from_email;
$email->FromName = $from_email;
$email->Subject = $subject;
$email->Body = $body;
$email->AddAddress($to);
if ($is_html == true) {
$email->IsHTML(true);
$email->Encoding = 'base64';
}
if ($attachments != null) {
foreach ($attachments as $attachment) {
$apath = $attachment["path"];
$aname = $attachment["name"];
$email->AddAttachment($apath , $aname);
}
}
$email->Send();
$status = "success";
}
catch (phpmailerException $e) {
$status = $e->errorMessage();
}
catch (Exception $e) {
$status = $e->getMessage();
}
return $status;
}
So I think I need to add this to my code but I'm not sure if I have to add this to the code. I was thinking that opendkim would just add the DKIM to the header. But its not.
$email->DKIM_domain = 'mydomain.com';
$email->DKIM_private = '/path/to/private_key';
$email->DKIM_selector = 'default';
$email->DKIM_passphrase = '1234567';
There are several ways you can implement DKIM signing.
With those properties in PHPMailer, where your client script needs
direct access to your private keys. Good when you have no control over the sending environment - e.g. on shared hosting, but it means each individual sending script is responsible for signing, which isn't ideal.
Getting your mail server to do the signing for you. Good when you have you own mail server and the ability to configure it - all mail that goes through it can be signed automatically, and you don't have to do anything at the client end.
Using a signing SMTP relay/proxy server in line
with your existing mail server, such as Hmailserver for Windows. Good when you have your own mail server, but don't have admin access to it, or it can't do DKIM.
The selector needs to match the key you're signing with, so if you have a selector called s1, you would expect the public key to be available in a TXT record called s1._domainkey in your domain's DNS. The matching private key just needs to be somewhere safe and web-inaccessible on the server.
The DNS and key arrangements are the same whichever signing mechanism you use. If you use PHPMailer's DKIM, you don't need openDKIM, but if you want to use OpenDKIM, you need to tell it which selector you want to use in its config. Some mail servers (like GreenArrow that I use) allow dynamic control of selectors via custom message headers, but I don't think OpenDKIM supports that. You may be able to set up virtual MTAs within postfix that allow something similar.
For a PHPMailer reference, look at the DKIM signing example provided, and the DKIM test in the test suite.

MailGun SMTP batch sending with Recipient Variables shows all recipients in To field

I am trying to get Batch Sending to work over SMTP, but even though I'm sending to multiple recipients and I've specified user variables (and the variables are getting replaced successfully in the email that is sent), every single recipient shows up in the To: field of the resulting messages at the receiver.
Per MailGun's documentation on Batch Sending...
Warning: It is important when using Batch Sending to also use Recipient Variables. This tells Mailgun to send each recipient an individual email with only their email in the to field. If they are not used, all recipients’ email addresses will show up in the to field for each recipient.
Here is an example of my SMTP headers...
To: foo#example.com, bar#example.com
X-Mailgun-Recipient-Variables: {
"foo#example.com":
{
"id":"12345",
"email":"foo#example.com",
"first_name":"Foo"
},
"bar#example.com":
{
"id":"45678",
"email":"bar#example.com",
"first_name":"Bar"
}
}
The resulting emails should only show one recipient per email in the To field. Am I missing something?
I started messing with this yesterday and I think I've found a solution.
The trick is to leave the To: addresses empty and add your recipients to the BCC line. Following that, add a custom header - To: %recipient%. $mail->send() will not complain, and the To: field in the received emails only show the individual recipient's email.
Code Sample:
$mail = new PHPMailer();
$mail->isSMTP();
$mail->Host = 'smtp.host';
$mail->SMTPAuth = true;
$mail->Username = 'yourUserName';
$mail->Password = 'yourPassword';
$mail->SMTPSecure = 'tls';
$mail->From = 'email#server.net';
$mail->FromName = 'John Doe';
$mail->addBCC('foo1#bar.com');
$mail->addBCC('foo2#bar.com');
$headerLine = $mail->headerLine('X-Mailgun-Recipient-Variables', '{"foo1#bar.com": {"first":"FooBar1", "id":1}, "foo2#bar.com": {"first":"FooBar2", "id": 2}}');
$mail->addCustomHeader($headerLine);
$headerLine = $mail->headerLine('To','%recipient%');
$mail->addCustomHeader($headerLine);
$mail->Subject = 'Hello, %recipient.first%!';
$mail->Body = 'Hello %recipient.first%, Your ID is %recipient.id%.';
if(!$mail->send())
{
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
}
else
{
echo 'Message has been sent';
}
I, too, was unsuccessful in getting this to work. I put in a mailgun trouble ticket. Here's the essence of their response:
The "Warning" in our documentation is actually for API only, not SMTP. The reason for this is that when using the API we form/create the email and that allows our service to separate and create a new email per each recipient in the To: field. When using SMTP though, we simply relay the message with the content that was submitted to our service, we don't actually create the message MIME from scratch.
To work around this, you can input %recipient% in the To: field. This will create a separate message for each address specified in the "RCPT TO" during the SMTP session with our server. Now, this is where things get a bit tricky, as my unfamiliarity with ASP SMTP connector starts to show here. In my research I haven't found a way to specify a RCPT TO using the ASP SMTP connector. It seems to rely on what you input in the To and doesn't provide a way to specify a To: field and RCPT TO: field.
When I try to use %recipient% as the TO variable, its built-in method raises an error, "CDO.Message.1 error '8004020c' At least one recipient is required, but none were found." I'm not familiar with other mailers but I would be surprised if any would allow this construct.
Had the same requirement for a WordPress site, here is something I came with for those who need it :
class PHPMailerForMailgunBatch extends PHPMailer {
public function createHeader() {
$header = parent::createHeader();
$header = preg_replace( "/To: .*\n/", "To: %recipient%\n", $header );
return $header;
}
}
and then
global $phpmailer;
$phpmailer = new PHPMailerForMailgunBatch( true );
// Config mailgun SMTP here
$mailgunBatchHeader = "X-Mailgun-Recipient-Variables: " . json_encode( $yourMailgunBatchVariables );
wp_mail( $emails, $subject, $content, [
$mailgunBatchHeader
] );

Yii: Called Mail() without being connected

I am trying to send email in Yii using PHPMailer. I am working on a live server. Here is my Configuration for email in Yii's main.php:
'Smtpmail' => array(
'class' => 'application.extensions.smtpmail.PHPMailer',
'Mailer' => 'smtp',
'SMTPAuth' => true,
),
Here is the error I get:
The following From address failed: noreply#mywebsite.com : Called
Mail() without being connected
Here is my controller Code:
$mail->IsHTML(true);
$mail->From = Yii::app()->params['adminEmail'];
$mail->FromName = empty($_POST['EmailForm']["from_name"])
Yii::app()->params['emailFrom'] : $_POST['EmailForm']["from_name"];
$mail->Subject = $subject;
$mail->Body = nl2br($message) . $mail->Body;
$mail->AddAddress($to);
$mail->AddCC($cc);
if (!$mail->Send()) {
Yii::app()->user->setFlash('error', $mail->ErrorInfo);
$this->redirect(array('update', 'id' => $id));
}
else {
Yii::app()->user->setFlash('success', "Email sent successfully!");
$this->redirect(array('update', 'id' => $id));
}
Any help?
You're enabling auth but not providing an id or password, which doesn't seem likely to work. You're also setting the submitter's address as the from address, which is also likely to fail as it's a forgery that will fail SPF checks. Set your own address as the from address and put the submitter in a reply-to.
Beyond that, enable debug output (SMTPDebug = 2 in PHPMailer - I'm not sure how you set that from Yii) so you can see the SMTP conversation.

Sending email using Zend Framework and PHP

I working on a form whereby when the user enter in their email account and click on send, an email will be sent to their email account.
I have everything worked out. Just that it doesnt send the email to my account. Anyone have any ideas? Is there a configuration that I left out or something?
This is the sample from my controller:
public function retrieveemailAction(){
$users = new Users();
$email = $_POST['email'];
$view = Zend_Registry::get('view');
if($users->checkEmail($_POST['email'])) {
// The Subject
$subject = "Email Test";
// The message
$message = "this is a test";
// Send email
// Returns TRUE if the mail was successfully accepted for delivery, FALSE otherwise.
// Use if command to display email message status
if(mail($email, $subject, $message, $headers)) {
$view->operation = 'true';
}
} else {
$view->operation = 'false';
}
$view->render('retrieve.tpl');
}
I recommend you use Zend_Mail instead of mail(). It handles a lot of stuff automatically and just works great.
Do you have a SMTP server? Trying to send mail without your own SMTP server could be causing the mail to not be sent.
This is what I use for sending mails using Zend_Mail and Gmail:
In Bootstrap.php, I configure a default mail transport:
protected function _initMail()
{
try {
$config = array(
'auth' => 'login',
'username' => 'username#gmail.com',
'password' => 'password',
'ssl' => 'tls',
'port' => 587
);
$mailTransport = new Zend_Mail_Transport_Smtp('smtp.gmail.com', $config);
Zend_Mail::setDefaultTransport($mailTransport);
} catch (Zend_Exception $e){
//Do something with exception
}
}
Then to send an email I use the following code:
//Prepare email
$mail = new Zend_Mail();
$mail->addTo($email);
$mail->setSubject($subject);
$mail->setBody($message);
$mail->setFrom('username#gmail.com', 'User Name');
//Send it!
$sent = true;
try {
$mail->send();
} catch (Exception $e){
$sent = false;
}
//Do stuff (display error message, log it, redirect user, etc)
if($sent){
//Mail was sent successfully.
} else {
//Mail failed to send.
}
First of all i would switch to using Zend_Mail. Second i would use a real mail account on an smtp server somewhere and send from that. A lot of times there are restrictions on sending from the server itself, but using an actual mail server usually fixes this.
There's a very useful screencast covering Zend_Mail available on ZendCasts
http://www.zendcasts.com/introduction-to-zend_mail/2010/02/
In line $mail->setBody($message);, change it to $mail->setBodyText($message);

Categories