Zend registry mail sender : How to debug? - php

Mail doesn't get sent properly. I need to help to properly debug as to why it isn't working on the server. Any solution?
$config = new Zend_Config_Ini(APPLICATION_PATH.'/configs/application.ini', APPLICATION_ENV);
$mailer = Zend_Registry::get('mailer');
if ($to) {
$mailer->setsendBcc(true);
}
// Add admin emails as recipient.
$to[$config->email->to] = '';
$mailer->setTo($to);
$mailer->setTokens($mailParams);
$mailer->setTemplate($template);
$result = $mailer->send();

Zend_Registry only stores stuff (eg. objects). We don't know what object is '$mailer'. It's not standard Zend_Mail object. You would need to check it - get_class($mailer) or look for Zend_Registry::set('mailer'.
You can always try:
try{
$result = $mailer->send();
}catch(Exception $e){
echo $e->getMessage();
}
Edit:
Also check if you are setting recipient correctly. It looks a bit odd in your code.

Related

PHP Imap get message body

I am connection to a mailbox and getting header information for each message like this:
$mailbox = new PhpImap\Mailbox(
env('MAIL_IMAP_PATH') . env('MAIL_FOLDER'), // IMAP server and mailbox folder
env('MAIL_LOGIN'), // Username for the before configured mailbox
env('MAIL_PASSWORD') // Password for the before configured username
);
$mailsIds = $mailbox->searchMailbox('ALL');
foreach($mailsIds as $mail_elem) {
$mail = $mailbox->getMail($mail_elem);
}
getMail gives me all the header infos without the body. I have checked now every single method which exists on $mailbox-> and there is no way to get the body. What am I doing wrong here?
Second approach is to use the stream from imap_open() and imap_fetchbody(). This feels more like a workarround because I connect a second time to the mailbox, but is also does not work:
foreach($mailsIds as $mail_elem) {
$imap_stream = imap_open(env('MAIL_IMAP_PATH') . env('MAIL_FOLDER'),
env('MAIL_LOGIN'), env('MAIL_PASSWORD'));
$message = imap_fetchbody($imap_stream, $mail_elem, 1.1);
}
I am getting an error:
imap_fetchbody(): Bad message number
Someone has an idea what is going on?
You have to get the body with the $mail object not the $mailbox object.
foreach($mailsIds as $mail_elem) {
$mail = $mailbox->getMail($mail_elem);
$message = $mail->textHtml;
}
This isn't the cause but the third parameter of fetchbody is a string, not a float, so write it like:
imap_fetchbody($imap_stream, $mail_elem, '1.1')
Your issue is probably about $mail_elem that's probably doesn't match with the index of the imap. In case they are UID, you need to add the flag FT_UID in the 4th paramates of imap_fetchbody.
Anyaway if you are planning to use imap_* library, I advise you to use this wrapper: php-taniguchi (it's quite documented and it has an example file).
The read() method is quite simple:
read(int $from, int $number, bool $details = false, bool $seen = false, bool $attachments = false)
Set all to true and you will get everything you want, it's quite easy:
$tmp = new \Taniguchi\Imap($account, $password, $url, $port);
$tmp->setSsl()->setValidate(false);
var_dump($tmp->read(1, 2, true, true, true));

Form to Email PHP Validation fallback using PHPMailer

i have a basic contact form on a website. i need to send the form results to 2 email addresses... 1) me, & 2) a confirmation to the person who submitted the form. the form results sent to the submitter has a different message in it.
i plan to add jQuery validation & Ajax but first i want to get the PHP to work. so i don't think i need a lot of PHP validation, just a basic - if critical fields are empty, then error message, as a fallback.
i'm using PHPMailer but unfortunately their documentation is sorely lacking for someone of my lack-of-php skills. but after much google'ing, i've been able to piece together something that mostly works. here is my code utilizing a small form (more fields to come later).
this DOES send the form to both email addresses - great!
the part i'm having trouble with is the validation & error/success messages.
if i just use the return $mail->send(); at the end of the function sendemail section, it sends fine. but if i try to submit the form without anything in the fields, nothing happens. so i tried adding this if(!$mail->send()) {...else...} piece i found somewhere, and it also works with valid form info, but not if empty.
so, what should i use instead of this? or would it be something different to the end if/else part?
<?php
if (isset($_POST['submit'])) {
date_default_timezone_set('US/Central');
require 'PHPMailer-5.2.26/PHPMailerAutoload.php';
function sendemail(
$SK_emailTo,
$SK_emailSubject,
$SK_emailBody
) {
$mail = new PHPMailer;
$mail->setFrom('myEmail#gmail.com', 'My Name');
$mail->addReplyTo($_POST['email'], $_POST['name']);
$mail->addAddress($SK_emailTo);
$mail->Subject = $SK_emailSubject;
$mail->Body = $SK_emailBody;
$mail->isHTML(true);
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
$mail->Username = 'myEmail#gmail.com';
$mail->Password = 'myPwd';
//return $mail->send(); //this works by itself, without IF/ELSE, but doesn't return error if empty form fields
if(!$mail->send()) {
return 'There is a problem' . $mail->ErrorInfo;
}else{
return 'ok'; // this works but i don't know why
}
} //end function sendemail
// form fields to variables
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
// from function sendmail to ASSIGN VALUES to...
/* $SK_emailTo,
SK_emailSubject,
$SK_emailBody */
if (sendemail(
'myEmail#address.com',
'First email subject',
'Form results to me...
<br><br>'.$message
)) {
sendemail(
$email,
'Second email subject',
'Confirmation email to person who submitted the form...
<br><br>'.$message
);
$msg = 'Email sent!';
} else {
$msg = 'Email failed!' . $mail->ErrorInfo;
}
} //end if submit
?>
as a sidenote, why does the return 'ok'; work? what does the 'ok' part attach to?
thanks!
//////////////////////// EDIT: NEW INFO BUT STILL NOT SOLVED ////////////////////////
based on the suggestions & edits by Mauro below (and in that posts comments), here is where i'm at now...
<?php
if (isset($_POST['submit'])) {
date_default_timezone_set('US/Central');
require 'PHPMailer-5.2.26/PHPMailerAutoload.php';
function sendemail(
$SK_emailTo,
$SK_emailSubject,
$SK_emailBody
) {
$mail = new PHPMailer(true);
$mail->setFrom('myEmail#gmail.com', 'My Name');
$mail->addReplyTo($_POST['email'], $_POST['name']);
$mail->addAddress($SK_emailTo);
$mail->Subject = $SK_emailSubject;
$mail->Body = $SK_emailBody;
$mail->isHTML(true);
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
$mail->Username = 'myEmail#gmail.com';
$mail->Password = 'myPwd';
return $mail->send();
} //end function sendemail
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
try {
sendemail(
'myEmail#address.com',
'First email subject',
'Form results to me...
<br><br>'.$message
);
sendemail(
$email,
'Second email subject',
'Confirmation email to person who submitted the form...
<br><br>'.$message
);
echo 'Email sent!';
} //end try
catch (phpmailerException $e) { //catches PHPMailer errors
echo 'There is a problem; the message did NOT send. Please go back and check that you have filled in all the required fields and there are no typos in your email address.';
echo $e->errorMessage();
}
catch (Exception $e) { //catches validation errors
echo 'There is a problem; the message did NOT send. Please either go back and try again or contact us at email#address.com';
echo $e->getMessage();
}
function validateEmpty($string, $name = 'name') {
$string = trim($string);
if ($string == '') {
throw new Exception(sprintf('%s is empty.', $name));
}
}
} //end if submit
?>
STILL...
1) Mauro suggested i log the error message using use error_log(). how do i do that? is that what produces the text file of error messages in the ftp directory?
2) Mauro also suggested using an $error & $success flag. what is that & how do i do it?
3) i want to have the custom error message in the above catch if the "name" &/or "email" fields (& possibly others) are simply empty. Mauro wrote the function validateEmpty code above, but i can't get it to work. do i have it in the wrong placement within the script or doing something else wrong with it?
3b) it looks to me like this function is just for the "name" field, do i have to duplicate it for the "email" field?
PLEASE REMEMBER...
i want to be able to have a SIMPLE validation here as a fallback in case Javascript/Jquery isn't working for some reason.
also note that the above DOES "send" the email correctly; so am now just trying to get the validation & error message to work right.
thank you for your time & expertise!
tl;dr: both statements evaluate to true. It's better to return true or false instead of strings and handle the message later.
First I'll take care of your question, then I'll make some suggestions on good practices.
When you use return x; in PHP and most languages, you're "sending" x back to where you called the function. So, when your code is executed it will be read as:
if('ok')
or
if ('Error info...')
PHP evaluates the condition on an if statement (this is the part between parenthesis) as true or false by converting it to the boolean type. The string to boolean conversion in PHP is basically as follows: any non-empty string evaluates as TRUE (follow the link, check first table, last column).
So, your function is returning 'ok' if it succeeds, 'Error info...' if it fails, these are both non-empty strings and thereof evaluated as true, so no matter if the first email sending attempt went well, your script will try to send the second one, and will always set $msg to 'Email sent!'.
Here's some advice on how to fix your script so it works (and looks) better:
As #Matt suggested it's always best to validate the data by yourself instead of relying on PHPMailer to do so. Despite PHPMailer will return an error if the destination address is invalid, it's a good practice not to even call the library if the email is not valid. So:
First, validate the data using javascript, so your user get's instant feedback.
Then, validate it using PHP (maybe create a new validate() function that may use filter_var() to validate emails.
Last, send the email only if the previous two were successful.
To follow your chain of thought, you should be evaluating if the string returned by sendemail() equals to 'ok' or not:
if (sendemail(...) == 'ok')
But, instead of evaluating two different strings ('ok' or 'Error info...') it's better if the function returned boolean values instead, and since PHPMailer's send() already does, just keep it as you have it commented:
return $mail->send()
Your last line is using $mail, a variable that you declared inside a function and you never made global, so it won't be available at that point and since you're trying to get a property (ErrorInfo) you'll be firing two PHP notices: Undefined variable and Trying to get a property from a non-object. You COULD just add global $mail at the top of the function and that will make it globally available (outside your function's scope) but this is considered a bad practice since in large pieces of code you might get confused.
Instead, a neater way of firing the error would be to throw/catch an exception:
function sendemail(...) {
// ... PHPMailer config ...
if ($mail->send()) {
return true;
} else {
throw Exception('Error: ' + $mail->ErrorInfo);
}
}
// later...
try {
sendemail()
$msg = 'Email sent!';
} catch (Exception $e) {
$msg = 'Email failed!' . $e->getMessage();
}
Here, if there's a problem with the emails sending, your function will throw a generic exception and the catch part will be executed.
EVEN BETTER
If you initialize PHPMailer like this:
$mail = new PHPMailer(true); // note the parameter set to true.
It will throw an exception by itself if it fails to send the email and you'll be able to catch the exception:
function sendemail(...) {
$mail = PHPMailer(true); // this line
// ... PHPMailer config ...
return $mail->send(); // just to return something, we aren't really using this value anymore.
}
// later...
try {
sendemail(...)
$msg = 'Email sent!';
} catch (phpmailerException $e) {
echo $e->errorMessage(); // Catch PHPMailer exceptions (email sending failure)
} catch (Exception $e) {
echo $e->getMessage(); // Boring error messages from anything else!
}
Never forget to read the docs!

Can not send email threw SwiftMailer with Mandrill

Since today, many of my php applications can not send email using SwiftMailer and different Mandrill accounts.
I've got this code, and the send function in the last if stop the script..
// Instance message
$message = Swift_Message::newInstance();
$message->setSubject("subject")
->setFrom(array('noreply#email.test' => 'test'))
->setTo(array('a_valid_email' => 'name'))
->setBody("test", 'text/html')
->setPriority(2);
$smtp_host = 'smtp.mandrillapp.com';
$smtp_port = 587;
$smtp_username = 'valid_username';
$smtp_password = 'valid_password';
// SMTP
$smtp_param = Swift_SmtpTransport::newInstance($smtp_host , $smtp_port)
->setUsername($smtp_username)
->setPassword($smtp_password);
// Instance Swiftmailer
$instance_swiftmailer = Swift_Mailer::newInstance($smtp_param);
$type = $message->getHeaders()->get('Content-Type');
$type->setValue('text/html');
$type->setParameter('charset', 'iso-8859-1');
//Here the send function stop event and I did not go inside the if
if ($instance_swiftmailer->send($message, $fail)) {
echo 'OK ';
}else{
echo 'NOT OK : ';
print_r($fail);
}
Thank you in advance to help me to solve this problem..
If your code used to work, and now doesn't work, and you didn't change your code, then it's probably not a problem with your code. Check your Mandrill account validity - sometimes they suspend accounts for suspicious-appearing usage.

Constant Contact API

I'm trying to write a simple Constant Contact script for adding and updating emails. The script is simple enough and should've ran smoothly. But when I start to include 'src/Ctct/autoload.php' the page just returns blank. I tried running it on another server and it works. But on my working server, it returns blank. It uses OAuth authentication from CTCT. I think it's a setting in the server, but I have no control over the server and any changes need to be forwarded to an admin, I just don't know what I need to change.
Here's the code:
require "Scripts/ConstantContact/src/Ctct/autoload.php";
use Ctct\ConstantContact;
use Ctct\Components\Contacts\Contact;
use Ctct\Components\Contacts\ContactList;
use Ctct\Components\Contacts\EmailAddress;
use Ctct\Exceptions\CtctException;
define("APIKEY", "*** Censored Media (18+ only) ***");
define("ACCESS_TOKEN", "*** Censored Media (18+ only) ***");
$cc = new ConstantContact(APIKEY);
// attempt to fetch lists in the account, catching any exceptions and printing the errors to screen
$lists = $cc->getLists(ACCESS_TOKEN);
$action = "Getting Contact By Email Address";
$Email = "asdf#asdf.com";
$FirstName = "Asdf";
$LastName = "Ghjk";
// check to see if a contact with the email addess already exists in the account
$response = $cc->getContactByEmail(ACCESS_TOKEN, $Email);
// create a new contact if one does not exist
if (empty($response->results)) {
$action = "Creating Contact";
$contact = new Contact();
$contact->addEmail($Email);
$contact->addList('1');
$contact->first_name = $FirstName;
$contact->last_name = $LastName;
$returnContact = $cc->addContact(ACCESS_TOKEN, $contact);
// update the existing contact if address already existed
} else {
$action = "Updating Contact";
$contact = $response->results[0];
$contact->addList('1');
$contact->first_name = $FirstName;
$contact->last_name = $LastName;
$returnContact = $cc->updateContact(ACCESS_TOKEN, $contact);
}
// catch any exceptions thrown during the process and print the errors to screen
if (isset($returnContact)) {
echo '<div class="container alert-success"><pre class="success-pre">';
print_r($returnContact);
echo '</pre></div>';
}
print '<p>'.$action.'</p>';
Again, this works on another server I tried, but doesn't work on my working server.
Any help would be appreciated.
Thanks!
Are you running PHP 5.3 or higher on the other server? Also did the domain change at all, if so that may throw an exception resulting in a blank page as your API key is domain specific. Feel free to shoot me an email and I will be glad to help you out with this - mstowe [at] constantcontact.com
-Mike

bcc multiple addresses with swiftmailer

Im using the below php code to send an email to one address and bcc 2 other addresses. It sends to the recipient fine but I can only get it to send to one of the 2 bcc addresses. (see comments in code for what ive tried)
Oddly enough though, $result comes back as 3 so it seems that its trying to send the second bcc email but it never comes through.
<?php
$tracker='tracking#pnrbuilder.com';
$subject = $_POST['subject'];
$sender = $_POST['sender'];
$toEmail=$_POST['toEmail'];
$passedInEmail=stripslashes($_POST['message']);
$passedInEmail=preg_replace('/ /',' ',$passedInEmail);
require_once('swiftLib/simple_html_dom.php');
require_once('swiftLib/swift_required.php');
$transport = Swift_MailTransport::newInstance();
$mailer = Swift_Mailer::newInstance($transport);
// Create the message
$message = Swift_Message::newInstance();
//turn the meesage into an object using simple_html_dom
//so we can iterate through and embed each image
$content = str_get_html($passedInEmail);
// Retrieve all img src tags and replace them with embedded images
foreach($content->find('img') as $e)
{
if($e->src != "")
{
$value = $e->src;
$newValue = $message->embed(Swift_Image::fromPath($value));
$e->src = $newValue;
}
}
$message->setSubject($subject);
$message->setFrom($sender);
$message->setTo($toEmail);
//this is my problem
$message->setBcc(array('tracking#pnrbuilder.com',$sender));
//as it is above only "sender" gets the email
//if I change it like this:
//$message->setBcc($tracker,$sender);
//only "tracker" gets the email
//same if I change it like this:
//$message->setBcc($sender);
//$message->addBcc($tracker);
$message->setReplyTo(array('flights#pnrbuilder.com'));
$message->setBody($content,'text/html');
$result = $mailer->send($message);
if ($result=3) {
echo 'Email Sent!';
}
else {
echo 'Error!';
}
?>
What is the proper way to do this?
You can find the swiftmailer tutorial here
example:
$message->setBcc(array(array('some#address.tld' => 'The Name'),array('another#address.tld' => 'Another Name')));
Try setting the names for the email addresses and see if it makes any difference.
This ended up being an issue on the server side, I contacted my hosting provider (GoDaddy) who were able to make some changes on their end fixing the problem. Thank you to all those who tried to help!

Categories