Tuesday, July 5, 2011

Sending e-mails with php

Sending e-mails can be easily done using the mail() function provided by php. This function has  4 main parameters and an optional parameter.

mail(arg1, arg2, arg3, arg4, arg5)

arg1 = email address of the receiver
arg2 = subject string of the email
arg3 = body of the email message
arg4 = headers of the email message

Following code segment demonstrates the use of this function.

1:  <?php  
2:  $email_recipient = "reciever@domain.com";  
3:  $email_subject = "This is a test";  
4:  $email_contents = "Hello, this is the content of this email message.";  
5:  $email_sender = "sender@domain.com";  
6:  $email_return_to = "sender@domain.com";  
7:  $email_content_type = "text/html; charset=us-ascii";  
8:  $email_client = "PHP/" . phpversion();  
9:  $email_header = "From: " . $email_sender . "\r\n";  
10:  $email_header .= "Reply-To: " . $email_return_to . "\r\n";  
11:  $email_header .= "Return-Path: " . $email_return_to . "\r\n";  
12:  $email_header .= "Content-type: " . $email_content_type . "\r\n";  
13:  $email_header .= "X-Mailer: " . $email_client . "\r\n";  
14:  $email_result = mail($email_recipient, $email_subject, $email_contents, $email_header);  
15:  if ($email_result) {  
16:       echo "E-mail sent successfully!";  
17:  } else {  
18:       echo "Failed to send e-mail!";  
19:  }  
20:  ?>  

Fill the receivers e-mail address with any valid email address. Then save this file in your apache servers www or htdocs directory with a file name ending with .php extension. Now access this file from a web browser. If every thing went fine the string
E-mail sent successfully!
will appear.
However I noticed that when I sent this emails to a Gmail based email account, the e-mail doesn't get into the recipients inbox even though the script shows that the message has been sent. I think the Gmail server drops the message due to some reason. I have no idea about that. When I sent an email to an email server which runs Zimbra email server, it worked fine.

No comments:

Post a Comment