I'm making my first site for a learning exercise as I've been a java back-end developer. I am setting up a user registration form and since this is going to be my user's first glimpse at my site, I want to make sure I handle things as robustly as possible. Through some trials I've come across and implemented almost all these solutions:
php's mail() function - this worked the first day i tested it and stopped working later. First time I realized sending mail wasn't a "given" simple task
pear mail class - implemented this tonight and is currently still working
pear smtp mail - read about this here. Makes me feel like I should be using smtp?
At this point I have realized sending email reliably is not quite as trivial as I originally thought. My question is what is the most reliable way to send mail, and what is the most robust way to handle exceptions? For instance if SMTP is the most reliable way, please explain why and provide a simple example with error handling.
For any of the errors that occur, are they errors where doing some automated retry would benefit? I understand that just because I send mail doesn't mean the person will get it, but I'm asking what the most robust solution is because I'm sure other people have done this 100 times over.
To prove I'm not just a lazy coder, this is what I've got so far which has been working - but I have no idea how robust this actually is (pear mail):
<?php } else if ($_SERVER['REQUEST_METHOD'] == 'POST') {
include('Mail.php');
include('Mail/mime.php');
$to = urldecode($_POST['email']);
if (preg_match('(\r|\n)', $to)) {
die('No email injection for you!');
}
$headers = array(
'From'=>'tag <me#mysite.com>',
'Subject'=>'Registration for mysite.com'
);
$text_body = 'boring text message';
$html_body = '<html>
<head><title>Welcome</title></head>
<body>
<p>slightly less boring message</p>
</body>
</html>';
//Utilize the mime class to generate mime body and add mime headers
$mime = new Mail_mime();
$mime->setTXTBody($text_body);
$mime->setHTMLBody($html_body);
$body = $mime->get();
$headers = $mime->headers($headers);
//Utilize the mail class to send the mime mail
$mail = Mail::factory('mail');
$mail->send($to, $headers, $body);
echo 'mail sent maybe?';
?>
EDIT:
Code sample using SMTP with error handling
<?php } else if ($_SERVER['REQUEST_METHOD'] == 'POST') {
include('Mail.php');
include('Mail/mime.php');
$to = $_POST['email'];
$to = urldecode($to);
if (preg_match('(\r|\n)', $to)) {
die('No email injection for you!');
}
$headers = array(
'From'=>'tag <me#mysite.com>',
'Subject'=>'Registration for mysite.com'
);
$text_body = 'boring text message';
$html_body = '<html>
<head><title>Welcome</title></head>
<body>
<p>slightly less boring message</p>
</body>
</html>';
//Utilize the mime class to generate mime body and add mime headers
$mime = new Mail_mime();
$mime->setTXTBody($text_body);
$mime->setHTMLBody($html_body);
$body = $mime->get();
$headers = $mime->headers($headers);
//Utilize the mail class to send the mime mail
$host = 'mail.mysite.com';
$port = '26';
$username = 'me#mysite.com';
$password ='myPassword';
$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>");
}
?>
There are typically several steps involved in sending mail:
Application: Put mail into queue of local delivery agent
Delivery agent: Send mail to configured SMTP server
SMTP server: Send mail to destination mail server
User mail application: Fetch mail from mail server
User: Click on mail, read it
PHP's mail() function puts the mail into the queue of the local mail delivery agent on unix. You'll only get an error (return value false) if that does not work. You do not get notified when the agent cannot deliver the mail further or any of the steps 2-5.
Using a direct SMTP connection to your SMTP server at least gives you an if the mail cannot be delivered to your SMTP server, which is more information than you get with mail(). What you don't get is information if the mail does not get read or is simply filtered out into a spam folder, or if the remote mail account does not exist (3-5).
To get to know that the remote account exists, you need to either parse the error response mails ("Undelivered mail returned to sender), or implement the full remote server SMTP connection and sending yourself (step 3), which I would not recommend.
To find out if the mail has been read, you could embed a "web bug", a tiny (potentially clear) image that is displayed in the HTML mail and notifies you that the mail has been displayed. You can use this to put sent mails into a database and mark them as read when your web bug image URL gets called. Mails that did not get read in X days can be seen as "not read" or "failed" - but the user can also simply be on vacation :)
Reliability & robustness
Your own mail server (step 3) automatically tries to re-send mails when the remote user's mail server is down. If that does not work, you'll get mails like "Mail delivery delayed for 24 hours", and another mail when it stopped doing that.
So once the mail is on your mail server, you can be sure that this server will do everything it can to deliver it.
Related
I have this mail script on my page: mail('myadress#server.com', 'New client added by user', 'test message');
but I do not receive anything! (of course I added my real adress). I tried it with 2 different adresses, looked in my spam folder, etc... just nothing. but the script executes just fine.
Is there any log I can view or invoke to see exactly what happened?
thank you for your help!
<?php
$to = "someone#example.com";
$subject = "Test mail";
$message = "Hello! This is a simple email message.";
$from = "someonelse#example.com";
$headers = "From:" . $from;
mail($to,$subject,$message,$headers);
echo "Mail Sent.";
?>
try this it will going to work for u ....
1) Check the return value from the mail() call:
$status = mail(...);
if (!$status) {
die("Mail failed");
}
If this fails, then PHP cannot even get the mail out the front door, and you'll have to figure out why - e.g. are you on a Windows box and haven't configured the mail options in php.ini?
2) Check your mail server's logs. Most Unix/Linux systems have a local mail server (the MTA) which will accept the mail from PHP. If it's misconfigured or having trouble, it may still accept the mail from PHP but then leave the mail to rot in a queue.
Perhaps your server's been placed on spam blackhole lists and it simply cannot deliver mail anywhere, which means you've probably got all of your test mails stuck in an outgoing queue that can't go anywhere.
Had to add the header "from" and use an email adress created on the server.
I am trying to send text messages to my phone from my server using php. I recently configured the server to send email, which it does (verified). It, however, goes into my spam box. When I try to send a message via sms I do not receive anything.
This is the script I am using:
$to = "myemailaddress#gmail.com";
$subject = "testing";
$body = "";
$headers = 'From: testemailaddress#gmail.com';
if (mail($to, $subject, $body, $headers)) {
echo("<p>Message successfully sent!</p>");
} else {
echo("<p>Message delivery failed...</p>");
}
The address that I am using for sms is myphonenumber#txt.att.net in the 'To' field.
I am going to go out on a limb here and say this is a authentication issue, maybe.
Is there anything I need to configure further? (i.e. php.ini)
Most email providers/servers today rely heavily on spam filtering / dnsbl. Your webserver is not a know mail server, and you probably did not set up SPF or anything.
An approach to avoid all those issues would be to utilize a Google Mail address (or any other providers). And instead of the PHP mail function use something more complex like Swiftmailer, which generates Mail headers that are less commonly autoclassified as spam.
See also: Using php's swiftmailer with gmail
This question should have a simple, simple answer, but I just can't seem to get it working. Here's the scenario:
I created a php page -> this one: http://adianl.ca/pages/member_application.php. Once the form is completed, it proceeds to http://adianl.ca/pages/member_application_action.php, puts the data into a MySQL db, & thanks the user for their interest. Anyway, the form works perfectly, except for one little thing: whenever someone fills out that form, I want an email to be sent to sbeattie#adianl.ca, informing them that the form was filled out, & the email would include the form components. The problem is, I can NOT get an email to be sent to that address, or any address truth be told. Having a php page send an email should be a simple thing to do, but it's really baffling me.
Can anyone help me with this? This particular problem has been troubling me since yesterday, & if anyone can help me with this...man, thank you soooooo much.
JP
$mail->IsSMTP(); // telling the class to use SMTP
$mail->Host = "mail.adianl.ca"; // SMTP server $mail->From = "webadmin#adianl.ca";
$mail->FromName = "Web Administration [ADIANL]";
$mail->AddAddress("sbeattie#adianl.ca");
$mail->AddCC("justinwparsons#gmail.com"); the #messageBody variable is just a string
If you want to have the email sent using the server's sendmail client, you can use mail.
If you want it to use another mail server, there are extensions to connect to an SMTP server. I use PHPMailer.
If mail doesn't work, it could be that the server is not set up to send email, or it could be that the mail server is rejecting emails sent from php, amongst other reasons.
this code can also be used to email in php so have a look, you can find many more examples of emailing in php look around
?php
$to = "recipient#example.com";
$subject = "Hi!";
$body = "Hi,\n\nHow are you?";
if (mail($to, $subject, $body)) {
echo("<p>Message successfully sent!</p>");
} else {
echo("<p>Message delivery failed...</p>");
}
I have a php mail script which works perfectly on a one host. However, when I attempt to use the same script on a network solutions host, the function returns true but no email ever sends.
//get mail function data
$case = $_POST['case'];
$to = addslashes(strip_tags($_POST['to']));
$message = addslashes(strip_tags($_POST['message']));
$subject = addslashes(strip_tags($_POST['subject']));
$message = addslashes(strip_tags($_POST['message']));
$from = "confirmation#website.co";
$headers = "From: $from\r\n";
//send email
if (mail($to,$subject,$message,$headers)){
//formatting for error message
$emailSent = "block";
$emailFailed = "none";
}
else //if the email fails to send
{
$emailSent = "none";
$emailFailed = "block";
}
?>
Does anyone know if different hosts require specific info in mail script?
This is a question for Network Solutions customer support. Sending mail from shared hosting servers is usually well locked down -- if they allow it at all, it's throttled. Also, calling mail just means the message was successfully passed to sendmail, not that the mail ever left the server. It could be sitting in a queue to be sent, it could have bounced for a million reasons beyond your control, etc.
Some hosts have this issue. On mine (Mosso), I had to adjust the last parameter (from) like so:
mail($to, $subject, $message, $headers, "-f".$from)
May not be the solution for NetSol but worth a try. I know some hosts disable the script and require using the smtp class to send mail.
This is assuming, of course, everything is correct with your DNS and MX records. If you're trying to send from an account that is different than the domain being sent from, some providers will automatically block that.
It maybe that they have not enabled php mail, but ask the host for specifics.
Looking at your code it is not cleaning the input sufficiently. take a look at the is_forbidden function here:
http://thedemosite.co.uk/phpformmailer/source_code_php_form_mailer_more_secure_than_cgi_form_mailers.php
I'm using PEAR's Mail package to send email from my script. I'm pretty sure I have everything connected and declared properly, but when the script runs, it just connects then immediately disconnects to my Mail server without actually sending the email.
From my Postfix logs:
Nov 18 16:15:49 mailer postfix/smtpd[30346]: connect from xxx-xxx-xxx-xxx.static.cloud-ips.com[xxx.xxx.xxx.xxx]
Nov 18 16:15:49 mailer postfix/smtpd[30346]: disconnect from xxx-xxx-xxx-xxx.static.cloud-ips.com[xxx.xxx.xxx.xxx]
What gives?
<?php
require_once('Mail.php'); // loads in PEAR Mail package
$mailer_params['host'] = 'mailer.example.com';
$mailer_params['port'] = 25;
$mailer_params['auth'] = true;
$mailer_params['username'] = 'user#mailer.example.com';
$mailer_params['password'] = 'password';
$mail =& Mail::factory('smtp', $mailer_params);
$headers = array(
'From' => 'user#example.com',
'Reply-To' => 'user#example.com',
'Subject' => 'Test Email'
);
$message = "whatever";
$mail->send('Test <other.user#example.com>', $headers, $message);
?>
I know my Postfix server works, since I have several other applications using it without problems. The user credentials are the same in this script as they are for those other apps.
My Postfix server is using SASL_auth (configured with CRAM-MD5), if that helps. I wish I had an error message or something on either the PHP side or the Postfix side to go on, but all it does is just connect then disconnect with no other explanation.
I had this problem a few days ago. Try $mailer_params['auth'] = 'CRAM-MD5' and also for extra information, try $mailer_params['debug'] and run the script from the command line. If that still doesn't work, try $mail_params['auth'] = 'LOGIN'.
Hope this helps.
Here is the first thing I'd try, see if you can get an exception error from PHP:
<?php
try {
require_once('Mail.php'); // loads in PEAR Mail package
$mailer_params['host'] = 'mailer.example.com';
$mailer_params['port'] = 25;
$mailer_params['auth'] = true;
$mailer_params['username'] = 'user#mailer.example.com';
$mailer_params['password'] = 'password';
$mail =& Mail::factory('smtp', $mailer_params);
$headers = array(
'From' => 'user#example.com',
'Reply-To' => 'user#example.com',
'Subject' => 'Test Email'
);
$message = "whatever";
$mail->send('Test <other.user#xxx.com>', $headers, $message);
} catch (Exception $e) {
echo "Exception: " . $e->getMessage();
}
And I have some other questions, out of curiousity:
You mentioned your postfix server works with other applications, are they on the same server? Is this a remote request, or an application on the same server as the mail
Can you reverse engineer anything on the working server to see what's being done differently?
Are you sending email from the same domain as what's on the server?
Some of the basis behind question 1 and 3 is the fact that a great deal of hosts either block or put restrictions on mailing. This is because spammers will create accounts and abuse them until they are banned. This makes sending mail difficult for the rest of us honest people, but it happens every day.
I hope this gives some food for thought, reply back and let's see if we can find the problem.