PDA

View Full Version : email() function alternative


tux
07-24-2013, 07:31 PM
My host has disabled the php email() function. I used it in a function to send account activation to new users.

email('To', 'Subject', "Body", 'Headers');

What alternative is there to use that is as simple as email().

Cheers, Paul

edbr
07-25-2013, 01:07 AM
the alternates to mail() are smtp in the forms of phpmailer , swiftmailer or PEAR.
for a quick fix maybe PEAR will do you . i will poost some code when i get some coffee :)

edbr
07-25-2013, 02:22 AM
try pear although i have had limited success due to server restrictions but easier to try

first go to pear packages and install Mail. rthis should add net and needed packages with it

you need some added paramaters to the script heres an example . they are much quoted on the web so i did a copy paste.

<?php
require_once "Mail.php";

$from = "Sandra Sender <sender@example.com>";
$to = "Ramona Recipient <recipient@example.com>";
$subject = "Hi!";
$body = "Hi,\n\nHow are you?";

$host = "mail.example.com";
$username = "smtp_username";
$password = "smtp_password";

$headers = array ('From' => $from,
'To' => $to,
'Subject' => $subject);
$smtp = Mail::factory('smtp',
array ('host' => $host,
'auth' => true,
'username' => $username,
'password' => $password));


with port

<?php
require_once "Mail.php";

$from = "Sandra Sender <sender@example.com>";
$to = "Ramona Recipient <recipient@example.com>";
$subject = "Hi!";
$body = "Hi,\n\nHow are you?";

$host = "mail.example.com";
$port = "465"; //25 is common
$username = "smtp_username";
$password = "smtp_password";

$headers = array ('From' => $from,
'To' => $to,
'Subject' => $subject);
$smtp = Mail::factory('smtp',
array ('host' => $host,
'port' => $port,
'auth' => true,
'username' => $username,
'password' => $password));

$mail = $smtp->send($to, $headers, $body);

if (PEAR::isError($mail)) {
echo("<p>" . $mail->getMessage() . "</p>");
} else {
echo("<p>Message successfully sent!</p>");
}

?>



I had some issues concerning the include path which was wrong. so it can be edited in php.ini if you have access or add at the top of your script

ini_set('include_path',
ini_get('include_path').PATH_SEPARATOR.'/home/HOST_ALIAS/php');


if (PEAR::isError($mail)) {
echo("<p>" . $mail->getMessage() . "</p>");
} else {
echo("<p>Message successfully sent!</p>");
}
?>[/PHP]

I had to revert to mail() as my server has silly restrictions on smtp!! cant win can you ?

make sure you have the port correct and 'auth' => true, if authorisation is needed

edbr
07-25-2013, 02:48 AM
also some docs on phpmailer http://code.google.com/a/apache-extras.org/p/phpmailer/wiki/UsefulTutorial

docs on swiftmailer http://swiftmailer.org/docs/sending.html

tux
07-25-2013, 08:28 AM
Thanks Edbr, I will check this out later. I did come accross Swift Mailer last night and got it working in a test page fine. But, cant seem to get it to work from inside my function. I'll post my code tonight when I get home from my boring day job! Maybe you can spot where I'm going wrong. Cheers again, Paul

edbr
07-25-2013, 09:07 AM
the code i gave will work with PEAR, i tested it so you just need slight changes. i find both phpmailer and swiftmailer abit of a bind (no pun intended) to modify to an existing function

tux
07-25-2013, 03:01 PM
Struggling to get this to work. What PEAR packages do I need to install? I have installed MAIL & PEAR(basic)

Here is my test code, can you see anything I've done wrong.....

<?php

ini_set('include_path', ini_get('include_path').PATH_SEPARATOR.'/home/OUR_ALIAS/php');

require_once "Mail.php";

$from = "SSDCC <noreply@ourwebsite.com>";
$to = "Paul <someuser@somewhere.com>";
$subject = "Please activate your account!";
$body = "Hello,\n\nYou need to activate your account, so please use the link below:\n\n
http://www.ourwebsite.com/activate.php?email=\"someuser@somewhere.com\"&email_code=\"xyz\"\n\n - SSDCC";

$host = "mail.ourwebsite.com";
$port = "465"; //25 is common
$username = "contact.ourwebsite.com";
$password = "password";

$headers = array ('From' => $from,
'To' => $to,
'Subject' => $subject);
$smtp = Mail::factory('smtp',
array ('host' => $host,
'port' => $port,
'auth' => true,
'username' => $username,
'password' => $password));

$mail = $smtp->send($to, $headers, $body);

if (PEAR::isError($mail)) {
echo("<p>" . $mail->getMessage() . "</p>");
} else {
echo("<p>Message successfully sent!</p>");
}
?>

My code hangs when I try to run it. Here are the last 3 errors in my error log.

[25-Jul-2013 15:29:38] PHP Warning: PHP Startup: Unable to load dynamic library '/usr/local/lib/php/extensions/no-debug-non-zts-20060613/uploadprogress.so' - /usr/local/lib/php/extensions/no-debug-non-zts-20060613/uploadprogress.so: cannot open shared object file: No such file or directory in Unknown on line 0

[25-Jul-2013 15:29:38] PHP Warning: PHP Startup: Unable to load dynamic library '/usr/local/lib/php/extensions/no-debug-non-zts-20060613/timezonedb.so' - /usr/local/lib/php/extensions/no-debug-non-zts-20060613/timezonedb.so: cannot open shared object file: No such file or directory in Unknown on line 0

[25-Jul-2013 15:29:38] PHP Warning: PHP Startup: Unable to load dynamic library '/usr/local/lib/php/extensions/no-debug-non-zts-20060613/imagick.so' - /usr/local/lib/php/extensions/no-debug-non-zts-20060613/imagick.so: cannot open shared object file: No such file or directory in Unknown on line 0

....making me think there are some files still need installing. There is no directory in the 'php' directory called 'extensions'. Any ideas!

edbr
07-26-2013, 01:18 AM
they are all php start up errors so
1 do you get them if you comment out the ini_get?
2 instead try require path to
require_once "../php/Mail.php"; or where ever that is

incase this is a server thing run a info() to see what is installed on your server re the named extensions in case it is a faulty compile as it must have changed recently.

if so the options of adding the any extensions is either manually via the php.ini file ( in folder php) or if you have a select php version option you can use that to activate the extensions you need, as well as alter the error reporting after it all works in production

tux
07-26-2013, 09:56 AM
Thanks Edbr, still struggled getting PEAR to work so checked with my Host who strangely pointed me back to PHP MAILER.

But, although I can get it to work in a test page and send email I still cant get it to work when combined with my register_user() function.

Can you give it a gander and see if you can spot what is wrong.

This is my register.php page......

<?php
include("includes/init.php");// the register_user() function is included via users.php which is included in init.php//
//logged_in_redirect();

// Registration Form Processing //////////////////////////////////////////////////////
if (empty($_POST) === false) {
$required_fields = array('username', 'password', 'password_again', 'first_name', 'last_name', 'email');
foreach($_POST as $key=>$value) {
if (empty($value) && in_array($key, $required_fields) === true) {
$errors[] = 'Fields marked with an asterisk are required';
break 1;
}
}

if (empty($errors) === true) {
if (user_exists($_POST['username']) === true) {
$errors[] = 'Sorry, the username \'' . $_POST['username'] . '\' is already taken';
}
if (preg_match("/\\s/", $_POST['username']) == true) {
$errors[] = 'Your username must not contain any spaces.';
}
if (strlen($_POST['password']) < 6) {
$errors[] = 'Your password must be at least 6 characters';
}
if ($_POST['password'] !== $_POST['password_again']) {
$errors[] = 'Your passwords do not match';
}
if (filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) === false) {
$errors[] = 'A valid email address is required';
}
if (email_exists($_POST['email']) === true) {
$errors[] = 'Sorry, the email \'' . $_POST['email'] . '\' is already in use';
}
}
}

if (isset($_GET['success']) === true ){
echo '<p>You\'ve been registered successfully! Please check your email to activate your account.</p>';
} else {
if (empty($_POST) === false && empty($errors) === true) {
$register_data = array(
'username' => $_POST['username'],
'password' => $_POST['password'],
'first_name' => $_POST['first_name'],
'last_name' => $_POST['last_name'],
'email' => $_POST['email'],
'email_code' => md5($_POST['username'] + microtime())
);

register_user($register_data);
header('Location: register.php?success');
exit();

} else if (empty($errors) === false) {
echo output_errors($errors);
}
?>
<form action="" method="post">
<p><span class="small">* Denotes required fields!</span></p>
<p>Username*:</p>
<p><input class="input" type="text" name="username" /></p>
<p>Password*:</p>
<p><input class="input" type="password" name="password" /></p>
<p>Password again*:</p>
<p><input class="input" type="password" name="password_again" /></p>
<p>First Name*:</p>
<p><input class="input" type="text" name="first_name" /></p>
<p>Last Name*:</p>
<p><input class="input" type="text" name="last_name" /></p>
<p>Email*:</p>
<p><input class="input" type="text" name="email" /></p>
<p><input class="left" type="image" src="images/register.gif" alt="Register" width="69" height="18"/></p><br>
<br class="clearsidefloat" />
</form>
<?php } ?>

and this is my register_user() function which adds user to DB and should email them an activation link......

function register_user($register_data) {
array_walk($register_data, 'array_sanitize');
$register_data['password'] = md5($register_data['password']);

$fields = '`' . implode('`, `', array_keys($register_data)) . '`';
$data = '\'' . implode('\', \'', $register_data) . '\'';

mysql_query("INSERT INTO `users` ($fields) VALUES ($data)");

ob_start();

include("class.phpmailer.php");

$mail = new PHPMailer();

//Your SMTP servers details

$mail->IsSMTP(); // set mailer to use SMTP
$mail->Host = "mail.website.co.uk"; // specify main and backup server or localhost
$mail->SMTPAuth = true; // turn on SMTP authentication
$mail->Username = "contact@website.co.uk"; // SMTP username
$mail->Password = "password"; // SMTP password It should be same as that of the SMTP user

//$redirect_url = "http://www.beta.website.co.uk/register.php"; //Redirect URL after submit the form

$mail->From = "contact@website.co.uk"; //Default From email same as smtp user
$mail->FromName = "NAME";

$mail->AddAddress($register_data['email'], $register_data['first_name']); //Email address where you wish to receive/collect those emails.

$mail->WordWrap = 50; // set word wrap to 50 characters
$mail->IsHTML(true); // set email format to HTML

$mail->Subject = "Hello ".$register_data['first_name'].", please activate your account.";
$message = "Hello ".$register_data['first_name'].",<br><br>Thank you for registering as a user with us. Before you can log into your account you will need to activate it using the link below.<br><br><a href=\"http://www.beta.website.co.uk/activate.php?email=".$register_data['email']."&email_code=".$register_data['email_code'].">http://www.beta.website.co.uk/activate.php?email=".$register_data['email']."&email_code=".$register_data['email_code']."</a><br><br>Regards, NAME";
$mail->Body = $message;
}

Cheers, Paul

tux
07-26-2013, 10:00 AM
Just to confirm, the function does add the user to the DB okay but just will not send the email!

tux
07-26-2013, 10:31 AM
Could this be something to do with the ob_start();?

edbr
07-27-2013, 01:15 AM
might be , looks ok at a glance. try echo out the $register_data['email'] with print_r or var dump to see if the values are being sent, then work back from there. i suspect they are not. or code an email address to test if the mailing side is at fault

edbr
07-27-2013, 04:02 AM
thinking again , if i fine upto including into the db, it can only be the collection of email address

tux
07-27-2013, 06:35 AM
I have tried hard coding an email address like this but still it won't send.

$mail->AddAddress("me@website.co.uk", "Paul");

It works in this test page.....

<?php

if($_GET['email'] == 'success'){
echo "Email sent successfully";
}elseif($_GET['email'] == 'fail'){
echo "Message could not be sent.";
}
if(isset($_POST['submit']) === true){

ob_start();

require("class.phpmailer.php");

$mail = new PHPMailer();

//Your SMTP servers details

$mail->IsSMTP(); // set mailer to use SMTP
$mail->Host = "mail.website.co.uk"; // specify main and backup server or localhost
$mail->SMTPAuth = true; // turn on SMTP authentication
$mail->Username = "contact@website.co.uk"; // SMTP username
$mail->Password = "password"; // SMTP password
//It should be same as that of the SMTP user

$redirect_url = "http://www.website.co.uk/testemail.php"; //Redirect URL after submit the form

$mail->From = "contact@website.co.uk"; //Default From email same as smtp user
$mail->FromName = "Name";

$mail->AddAddress("me@website.co.uk", "Paul"); //Email address where you wish to receive/collect those emails.

$mail->WordWrap = 50; // set word wrap to 50 characters
$mail->IsHTML(true); // set email format to HTML

$mail->Subject = "Hello Paul, please activate your account.";
$message = "Hello Paul,<br><br>Thank you for registering as a user with us. Before you can log into your account you will need to activate it using the link below.<br><br>
<a href=\"http://www.website.co.uk/activate.php?email=me@website.co.uk&email_code=hsywrf8w38yrrg98\">http://www.website.co.uk/activate.php?email=me@website.co.uk&email_code=hsywrf8w38yrrg98</a>";
$mail->Body = $message;

if($mail->Send()){
header("Location: $redirect_url?email=success");
}
if(!$mail->Send()){
header("Location: $redirect_url?email=fail");
echo "Message could not be sent. <p>";
//echo "Mailer Error: " . $mail->ErrorInfo;
}
}

?>

<form action="" method="post">
<input type="submit" value="Send" name="submit">
</form>

But not when in the function, its driving me mad!

edbr
07-29-2013, 01:07 AM
yes i got frustrated with php mailer , i will try to replicate if i get time. it was the reason i suggested PEAR. I also struggled at first but it was often the path that gave me issues